EmbLogic's Blog

what is the compilation process in c program.

Compilation process in C program

There are four phases for a c program to be execute,

1.pre-processor

2.compiler

3.assembler

4.linker

let’s start with the first one,

#Pre-Processor- The pre-processor removes the comments and include header files in source code, replace macro name with code.

Basically, it is a program that processes its input data to produce output that can be used by another program as its input. Obviously, compiler is the next one,

#Compiler- A compiler is a program that processes your written data which is in your language convert into machine language i.e. binary form(0 &1).

Basically, it generates the assembly code of the file, it converts the (.i) file into the (.s) file. Any file entering into compiler program passes through lexical analysis, syntax analysis, intermediate code generation, code optimization, object code generation. And the next one is,

#Assembler- An assembler is a program that converts assembly language or assembly code into machine code or object code. Assemblers are similar to compilers in that they produce executable codes.

It converts the (.s) file into the (.o) file. Finally, the last one is,

#Linker- A linker is a computer program that takes one or more object files generated by a compiler and combines them into one, executable program.

There are two types of linker i.e. static linking and dynamic linking.

Static linkingis the result of the linker copying all library routines used in the program into the executable image.

Dynamic linking is done during load or run-time and not when the exe is created.

It converts the (.o) file into the executable file for example (.elf) file.

Now let’s create a simple program,

First we write our program in the vim editor* *(you can use any editor)

#include<stdio.h>

int main()

{

printf(“Hello, This is Ritik Sharma\n”);

return 0;

}

save the file with a name and (.c) extension and then exit from the vim editor

now compile the file with the compiler for example gcc,

then execute the file which is ./a.out and you can see the output as given below,

Hello, This is Ritik Sharma

nice! You got the output. If any error occurred during compiling the program then note that error and try to correct that error.

_THANK YOU_

 

Posted in Data Structures with C | Leave a comment

Basic of c language

Introduction to C:-

C is a general purpose high level programming language used to develop portable applications and firmware. It is originally designed to develop system software and operating systems. C was invented by Dennis’s Ritchie at bell labs in the 1972s. C has a primary application of Unix operating system. C have a main features low-level access to memory, simple set of keywords and clean style. Because of these features, this language is a suitable language for operating system development. After C, I follow the syntax of many developed language PHP, Java, Java script etc. C was initially used for system development work, particularly program of the system operating system. C was adopted a system language because it produce code that runs nearly as fast as the written code of assembly language.

Developing programs using c requires software called integrated development environment (IDE) such as turbo c, codeblocks, visiual studio etc. the integrated development environment mainly three programs:

1. Text editor 2. Compiler 3.Debugger.

1 . Text editor :- it is used to type of instructions of program which is called of source code. Source code is stored in c file.

2. compiler:- it is used to translate instructions of program into machine language which is called binary code.

3. Debugger:- it is used to find bugs(errors) within programs.

Keyword:- keywords are p redefined word for performing various type of c. there are total 32 keywords

available in c. example :- char,float,int etc.

Variable:- variable are new words created by us for storing data. Its value changes during execution programs. Example :-a,b,c, num, sum etc.

Constant:- Constant refer to the fixed value of that does not change during execution of program. No matter where we use it in program, it meaning always remains same. Example :-5, 34.33, -71 etc.

Operator :- symbols that are used to perform operations between variable are called operators. Example:- +,-,*, / = etc.

Application and Uses Language:-

C is mainly used to develop system software such as operating system, compiler etc. But it can also be used for developing and kind of application software such as commercial, scientific, games etc.

Advantage of C Language:-

1. C language is a building block for many other currently known language. C language has variety of data types and powerful operator. Due to this, program written in c language are efficient,fast and easy to understand.

2. C is highly portable language. This means that c programs written for one computer can easily run on another computer without any change or by doing a little change.

3. There are only 32 keywords in ANSI c and its strength in built in functions,several standard functions are available which can be used for developing program.

Disadvantage of C:-

1. C does not have concept of oops, that’s why c++ is developed.

2. there is no run time checking in c language.

3. there is no strict type checking.

4. C does not have the concept of name space.

5. C does not have the concept of constructor or destructor.

 

Posted in Data Structures with C | Leave a comment

Shell & Shell Scripting

Shell & Shell Scripting

Shell is the medium or intermediator between the user and computer and act as an form of wrapper around the Operating system hence termed Shell. It helps the user to connect with the system kernels to perform huge and various task hence the shell scripting is needed. Shell interpret the commands that acts as an interface for the access to operating system services such as Unix, Linux, Windows etc. Shell is the layer of programing on the outermost layer of the operating system which interprets commands and send necessary system calls to the kernel for execution of program. Today, there are many shells avavilable like bash, bsh, ksh, csh, zsh powershell etc. Among all the shells “bash” is the most and frequently used shell world wide. Shell is capable of automate very complex sequences of commands and most linux system are designed to be updated from typed in commands i.e. from shell. Shell also powers many of graphical commands that is run by users. Shell plays the most important role to better understand the computer. See below figure to better understand.

Shell figure

Linux Shell

Shell classified in two categories.

  • Command Line Shell

  • Graphical shell

Command Line Shell:- Shell can be accessed by user using command line interface i.e. called Terminal in linux or Unix operating System. And Command Prompt in Windows operating System. Shell takes commands by user and call operating system to run those commands.

For Example: ls, ls -a, cat, etc.

Graphical Shell:-Graphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing.

Shell Scripting

Usually, shells accepts commands as input from users and execute them. But sometimes we need to perform multiple operations using several commands hence to perform these operations we have to type all commands one by one to get the result.

So to avoid repetitive work and run all commands at once we need Shell Scripting. In Shell scipting we group number of commands in a file, and when you run shell script file, shell will executes the commands in the script file order. A shell script have syntax just like any other programming language.

Shell scripts consist below mention elements:-

  • Shell Keywords

  • Shell commands

  • Functions

Advantages of Shell & Shell Scripting

  • Shell can automate very complex sequences of commands.

  • Shell allows you to create new commands using other commands.

  • Scripting helps you to add new functions easily to the shell.

  • Writing shell scripts are much quicker and easier.

  • Interactive Debugging.

Disadvantages of Shell &Shell Scripting

  • Graphical environment is not userfriendly which is why scripting is being used less.

  • Provide minimal data Structures.

At last we must say, learning the Shell Scripting can help you better understand your computer.

 

Posted in Shell Scripts | Leave a comment

Installation to Fedora 29

Installation to Fedora 29

  • Following are the minimum requirements for Fedora 29 workstation :-

  • Recommended 2 GHz Dual Core processor.

  • 2 GB RAM.

  • 15 GB unallocated Hard Disk.

  • Bootable Media (USB / DVD).

  • Installation steps :-

(Step1) :- Download the fedora 29 workstation ISO file :

Once the ISO file is downloaded ,then burn it either in USB or DVD and make it bootable.

(Step2) :- Boot your system with bootable media (USB or DVD) :–

Reboot your system.Set the boot medium as USB or DVD from Bios settings so system boots up with bootable media.

(Step3) :- Choose Start Fedora-Workstation-Live- 29 :–

When the system boots up with bootable media then to begin with installation on your system’s hard disk, choose “Start Fedora-Workstation-29 Live

(Step4) :-Select Install to hard drive option :–

Select “Install to Hard Drive” option to install Fedora 29 on your system’s hard disk, you can also try Fedora on your system without installing it, for that select “Try Fedora” Option.

(Step5) :- Choose appropriate language for your Fedora 29 Installation :–

In this step choose your language which will be used during Fedora 29 Installation.

(Step6) :- Choose Installation destination and partition scheme :–

  • In this step we will choose our installation destination, means on which hard disk we will do installation.
  • In the next screen we will see the local available hard disk, select the disk that suits your installation and then choose how you want to create partitions.
  • If you choose “Automatic” partition scheme, then installer will create the necessary partition for your system automatically but if you want to create your own customize partition scheme then choose “Custom” option.CLICK ON DONE !
  • Now I show u that how to create LVM(Local Volume Manager) based custom partitions :–

In my case,

I have around 779 GiB unallocated hard drive, so I will be creating following partitions on it :-

  • /home         >>> 450 GiB
  • /(root)        >>> 240 GiB
  • boot/efi     >>>2 GiB
  • /boot         >>> 2 GiB
  • /var           >>> 50 GiB
  • swap         >>> 24 GiB

CLICK ON DONE ! AND CHOOSE “ACCEPT CHANGES”.

(Step7) :- Select the time zone and begin installation :–

  • Here you can select the time zone which suits to your system and click on “Begin Installation”.
  • In this step we can see Fedora 29 Installation has been started and it is in progress.
  • Once the Installation is completed, you will be prompted to restart your system.
  • Click on Quit and reboot your system.

Don’t forget the Change boot medium from Bios settings so your system boots up with hard disk.

(Step8) :- Set User name and Password and Start using Fedora 29. :–

  •  Now specify the local account (user name) and its password, later this account will be used to login to the system.
  • Click on Next

And finally, we will get below screen which confirms that we are ready to use Fedora 29.

  • Click on “Start Using Fedora

Posted in Project 00: Linux System / Network Administration | Leave a comment

C Language

Basic of C language

C is a general-purpose programming language. It is extremely popular, simple and flexible. It is machine-independent, structured programming language which is used extensively in various applications.C is the basics language to write everything from operating systems (Windows and many others) to complex programs like Oracle database, Git, Python interpreter and more.

Where is C used? And key Applications….

  1. Most of the applications by Adobe are developed using ‘C’ programming language.
  2. It is used to develop databases. MySQL is the most popular database software which is built using ‘C’.
  3. It is used in developing an operating system. Operating systems such as Apple’s OS Microsoft’s Windows, and Symbian are developed using ‘C’ language. It is used for developing desktop as well as mobile phone’s operating system.

  4. C’ language is widely used in embedded systems.

  5. It is used for developing system applications.

why it is necessary to learn C language first ??

  1. It is mother language of all other language like Pyhton , Java,PHP etc …..

  2. It is low programming level language close to machine language.

  3. It is procedure and structure oriented language.

  4. With the help of C language hardware resources most efficiently used because it is highly compatible with hardware..

  5. It is highly portable. So it can be used more than one hardware with same source code.

Best carrier option : -

The career in C programming is good. Mainly the programmers need the technical skill in C programming to write and develop the software programs that can be used across different platforms to control the flow of data to retrieve or store. C programming has a very good career like opportunities in different field like robotics, Artificial intelligence, Machine learning etc .The C programmers not only work in the field of computer only, but they can also pursue their career in Education, teaching, Government sectors, etc. as some of the programmers have a different specialization like in system analysis, project management, information systems, etc. The career in C programmers is continuously growing because of the rapid social, business and technology changes.

Real life application of C language

If you buy a feature loaded car then

  • tire pressure detection systems

  • sensors (oxygen, temperature, oil level, etc.)

  • memory for seats and mirror settings.

  • dashboard display

  • anti-lock brakes

  • automatic stability control
  • climate control

  • child-proof locks

  • keyless entry

  • heated seats

  • airbag control

All these lies under embebbed system programmed in Embedded C language.

Conclusion: -

The world is running on C-powered devices. Its versatility, efficiency and good performance makes it an excellent choice for high complexity data manipulation software.It’s closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software. The C programming language doesn’t seem to have an expiration date.

The fact that many programming languages today are better than C for their intended use doesn’t mean that they beat C in all areas. C is still unsurpassed when performance is the priority.

 

Posted in Uncategorized | Leave a comment

Dynamic Memory Allocation

DYNAMIC MEMORY ALLOCATION

In industry memory management is very important.

There are two types of memory which is used by the program, one is Stack segment and another is Heap segment.

Stack is a special area of Computer’s memory which stores the temporary variables created by the functions. In stack variables are stored in run time. It is a temporary storage memory.

Heap is a memory used to store global variables. Heap is not managed by the CPU unit. It supports dynamic memory allocation.

Dynamic memory allocation is done with malloc(), calloc() and realloc() function.

Malloc: malloc is used to allocate a block of memory in the heap segment. Malloc allocates the memory at run time. Malloc allocates the memory in the heap segment. Dynamic memory is not cared by the CPU, so it’s required to free the memory after the use to prevent the memory leakage.

Syntax:

ptr=(int*/char*)malloc(byte-size);

where ptr is a pointer type of variable which points the base address of the allocated memory in heap segment. After that is pointer typecast of the data.

If we allocates the ‘0’ bytes to the malloc then also it reserve some memory which is of size 32Kbytes.

The usable size of the malloc is checked by the malloc_usable_size which is 24Kbytes, and it keeps extra 8bytes with it which is chunk size.

Working of malloc function:

When we gives the size to allocate then it checks the threshold of malloc and then checks it in memory pages if available then then it allocates the memory blocks otherwise memory mapping comes into the picture(mmap).

Malloc allocates the memory in heap segment which have fixed size of 130Kbytes.

When we allocates the memory then it points the address of the page which is of 130Kbyte’s size if the requirement is more than heap then the size of heap then it calls the extra memory by mmap.

On the successful of malloc it returns the address of the allocated space. On the failure of malloc it returns the NULL .

Calloc: calloc is used to allocate dynamic memory. Dynamic memory is allocated on run time .

Calloc is similar to malloc the difference is, that the default values of the allocated blocks are zero in calloc and in malloc the default values are garbage.

Realloc:realloc is used to allocate the memory on run time whenever the extra memory required on the run time.

Syntax:

ptr_new=(typr-caste)realloc(ptr,new_size in bytes);

where ptr_new is the address of the new allocate space, ptr is the previous size of allocated memory.

Working of realloc function:

when realloc function is used then first it checks the available space in that page if the required space is available then it added the requested blocks of memory.

If the size is not available then an extra page comes through the memory mapping concept and reallocates the space requested and it copies the data of the current address to new allocated space and frees the previous memory.

Malloc is slightly faster than Calloc than Realoc.

Posted in Uncategorized | Leave a comment

gcc compilation process

 

Gcc compiler

Compilation Process:

Any c file, a user wants to compile is not directly compiled. For example, there is c file having a name hello.c, this hello.c file is not directly provided to the compiler. Hello.c file first of all provided to the gcc preprocessor , this preprocessor converts this hello.c file into hello.i file. This hello.i file consists of two file stdio.h and hello.c file. The combination these two files together makes a new file which is hello.c file . This hello.c file is provided to the gcc compiler. The gcc compiler is basically a two pass compiler which passes file two times . Then the file moves to the lexical analysis ,this lexical analysis breaks the content of file into tokens , then the tokens are provided to the syntax analysis which analysis all the tokens of file according to the c format ,this analysis gave us an errors ,saying that tokens used are appropriate or not .After the analysis process, file passes through the intermediate code generation, code optimization and object code generation. After the 2-pass compilation process, the format of file changes into different format which is in hello.s format .The output of the compiler is provided to the assembly, which is in the format of hello.s file. This hello.s file through assembly passes to the assembler. Assembler converts this hello.s file into hello.o file. This hello.o file passes through the symbol table, data segment and code segment process . After passing through these processes, file is provided to linker .The output of linker generates a new file named as a.out file which is in executable format. This executable file is then provided to the executable linkable format (elf), data segment and code segment.

After this whole process loader loads the file into the RAM. File spreads out in the ram. Ram is basically a process context (virtual address space content ) which consists of stack segment, file descripter, data segment and code segment. Stack segment consists of local variable of the file. File descripter consists of three ports 0,1,2 . These three ports are connected to the standard input, standard output and standard error respectively via stream. Stream is used for moving data wheather for input, output or for error. Standard input is used for entering the data to the port 0. standard output takes out the data from port 1. And standard error is to takes out the error from port 2. Data segment consists of various variables like global variable, static variable, extreme variable, register variable, volatile variable, constant variable, macros variable and preprocessor directive. Code segment consists of compiled code. Stack segment, file directive, data segment and code segment all these have some logical addresses.

 

Posted in Data Structures with C | Leave a comment

Compiler process in ‘C’

Compiler is a software ,which is use for converting the code language to machine language.

the c programe are work in 5 process-

  • Preprocessor
  • compiler
  • assembler
  • linker
  • loader

Preprocessor-In the preprocessor a preprocessor directive (#) and a header file (stdio.h)

int main() the programe are start for exicute.

after that type a code “hello world” use c libraries.

and the last format is return 0; in this point the programe is success full exicute.

after that this process the preprocessor also give a hello.i file.

in hello.i file are include 2. files stdio.h+hello.c file.

Compiler-in this process the compiler are work in 2 pras.

1.pras 

  • lexical analysis
  • syntax analysis
  • intermediate code genration
  • code optimization

the 1st pras process is create a symbol table.

2. pras

  • lexical analysis
  • syntax analysis
  • intermediate code genration
  • code optimization
  • object code genration

and the 2nd pras is compile the code use symbol table.

and compiler create a ” hello.s” file.

Lexical analysis-in lexical process the code is break in tokken,

example- hello world  –>h e l l o w o r l d. 

Syntax analysis-in syntax process the cheak the code in right format.

example (),:,<,>,”””.

Intermediate code genration-in intermediate code genration process the code token also arrange in  highest priority order.

Code optimization-in code optimization process the compiler also optimize code  and resolve  minor error.

Object code genration-in object code genration process the compiler are genrate the full code in objective form.

 in this process the fully code also link of symbol table.

in hello.s file, include “code,data segment,symbol table”.

Assembler-   after the compiler process the code also convert in  assembly language.

and make a hello.o file in .o file include links,data ,code, refrence symbol table.

linkerthe linker process  also linked the code for c library and symbol table.

and make exicutable linkable format and output file-> a.out.

in this file stored in secondry memory .

programe  compiling process is complete

Loader- the programe exicutable linkable format file (secondry memory) to process context (primary memory) through loader.

Posted in Data Structures with C | Leave a comment

Precision Time Protocol

The Precision Time Protocol (PTP) is a protocol used to synchronize clocks throughout a computer network. On a local area network, it achieves clock accuracy in the sub-microsecond range, making it suitable for measurement and control systems.[1]

PTP was originally defined in the IEEE 1588-2002 standard, officially entitled “Standard for a Precision Clock Synchronization Protocol for Networked Measurement and Control Systems” and published in 2002. In 2008, IEEE 1588-2008 was released as a revised standard; also known as PTP Version 2, it improves accuracy, precision and robustness but is not backward compatible with the original 2002 version.[2]

“IEEE 1588 is designed to fill a niche not well served by either of the two dominant protocols, NTP and GPS. IEEE 1588 is designed for local systems requiring accuracies beyond those attainable using NTP. It is also designed for applications that cannot bear the cost of a GPS receiver at each node, or for which GPS signals are inaccessible

Posted in Uncategorized | Leave a comment

gcc- tool chain

GCC is a popular tool chain that can generate executables for wide range of architectures including x86, ARM v4/v5/v6/v7, and many others. In personal computers GNU GCC is a compiler that compiles an application written for LINUX X86 PC. When the host and target architectures are different, the tool chain is called ” cross compiler “.
You may come across different tool chains to cross compile your application for ARM like arm-none-linux-gnueabi, arm-none-eabi, arm-eabi, arm-fsl-linux-gnueabi-gcc etc.

Tool chains have a loose name convention like arch [-vendor] [-os] – eabi
arch – refers to target architecture (which in our case is ARM)
vendor – refers to toolchain supplier
os – refers to the target operating system
eabi – refers to Embedded Application Binary Interface

some illustrations as follows :

arm-none-eabi – This tool chain targets for ARM architecture, has no vendor, does not target an operating system and complies with the ARM EABI.
arm-none-linux-gnueabi – This toolchain targets the ARM architecture, has no vendor, creates binaries that run on the Linux operating system, and uses the GNU EABI. It is used to target ARM-based Linux systems.

So, If you built your application “helloworld.c” with arm-none-linux-gnueabi-gcc (or) arm-fsl-linux-gnueabi-gcc, executable will work on your ARM target board as the tool chain has only difference in vendor.

Posted in Uncategorized | Leave a comment

Remote Access to Linux

Our office network contains several Windows computers and one Linux desktop. I recently switched from Windows to Linux for most of my work, and have enjoyed its many advantages. But as I became more dependent on the information and applications stored in that computer, I wondered how I could use that system from other locations. This article describes how I solved that problem and shows how you can set up remote access to Linux computers.

My Linux distribution is SUSE Linux 10.1. Our network consists of a Linksys WRT54GS wireless router, a Linksys WMP54G wireless access card in the Linux computer, a Linksys WRE54G repeater to boost the signal quality, and a Maxtor Shared Storage drive, so all the computers have shared storage. My goals were to access the files on both Linux disks (local hard drive and shared storage) and to run applications on the Linux system from any other computer on the Internet. I accomplished these tasks in three largely independent ways, which you can mix and match to suit your needs:
· Secure Shell (SSH)
· File Transfer Protocol (FTP)
· SUSE Linux VNC-based remote administration feature
As a starting point, I assume that your Linux installation and network are already set up, using components similar to mine. The shared file server is not required, but if you have one, see the sidebar (editor: insert link here) for instructions about mounting this resource.

SSH

SSH is the Secure SHell service. It is similar to telnet, but with more features, and every transaction is encrypted. Using SSH, you are provided a shell nearly identical to one available locally. This provides all of the command line functionality of Linux. Also, curses applications (like YaST) work through SSH. Keep in mind that because the shell is identical to one available locally, you cannot move files between your SSH client’s system and the SSH server system. For file transfer, FTP is required.

To set up SSH, open up the YaST Control Center and use the Software Management module to make sure you have the package openssh installed. Next, enable the SSH server on your system by selecting YaST’s System tab, opening System Services, and ensuring that the service ssh is enabled.

When you want to access this SSH server from a remote computer, use the ssh command in Linux and Mac OS X. Type the following at the remote computer:

ssh

The IP address you use here is either: your company’s static IP address, or the address assigned to your router by your Internet service provider (ISP). If you do not know the IP address of your router, you can find it by visiting www.whatismyipaddress.com.

For Windows, the application PuTTY is the preferred SSH client.

FTP

FTP is the File Transfer Protocol. It can be used to move files between where you are (the remote client) and the computer you’re connecting to (your office Linux system).

To set up your Linux computer as an FTP server, use YaST’s Software Management module to make sure you have the vsftpd package installed. Then, check the System Services module to verify that vsftpd is enabled.

Before you can begin to use the FTP server properly, it needs to be configured. The default configuration is for a read-only anonymous server, without permission to see the directory tree. This is fairly useless. You probably want to modify FTP access to allow login with the normal accounts of the system and with write permissions. The general configuration file that vsftpd uses is /etc/vsftpd.conf, which is only writable by root. Make the following changes to this file, which appear below in the same order as in the file.
· Uncomment the line that says “#write_enable=YES”. This permits actions which modify files on your system.
· Uncomment and change the line “#ftpd_banner=”Welcome to FOOBAR FTP service.”” if you want to. This is a message sent to the client when they log in.
· Uncomment the line “#local_enable=YES”. This allows login with the user accounts of the system. These are listed in /etc/passwd.
· Change the line “anonymous_enable=YES” to say “anonymous_enable=NO”. There is no need to allow random passersby to access your system.
· Uncomment the lines “#log_ftp_protocol=YES” and “#xferlog_enable=YES”, which will enable logging of all actions.
To access the FTP service from a remote computer, you can use a command line FTP client. Many are available for Windows, Mac OS X, and Linux. At the FTP command line, just type

ftp

Also, most web browsers support the FTP protocol directly, so you can type ftp:// into the browser bar. Personally, I recommend a GUI FTP tool rather than command line or browser-based utility. I like Filezilla on Windows.

Linux Remote Desktop

Remote desktops create an “almost like you are there” experience for remote users. With a high-speed connection, this is a very nice way to work on your Linux system from another location. SUSE’s remote desktop is based on VNC. To begin, make sure that the VNC-related packages (tightvnc, xorg-x11-Xvnc, kdenetwork3-vnc) are installed on your Linux computer. Next, start the Remote Administration module on the YaST System tab, choose “Allow Remote Administration” and click “Finish”.

To access your Linux system from a remote computer, use a VNC client (RealVNC, TightVNC, UltraVNC, Krdc or KVPnc) and connect to port 5901 of your router’s IP address. If you are somewhere that a VNC client is not available (and installing one is not desirable) the SUSE VNC server allows another connection method. Type :5801 into a standard web browser, and a Java applet will start that remotely mimics your Linux desktop.

Setting up the Router with Port Mapping

There is one last crucial step before any of this can work. Your router must be modified to allow incoming connections to the services you just established. Using a web browser on your office network, enter the IP address of your router’s control panel. (This is usually something like 192.168.1.1.) You want to configure port forwarding, also called port mapping. On the Linksys WRT54GS router, this is the first tab under Applications and Gaming. Set your router to forward ports 20, 21, 22, 5801, and 5901 for TCP and UDP traffic, for any application, to the IP address assigned to the Linux computer inside your network. (This address is probably something like 192.168.1.6.) Ports 20 and 21 are for FTP, port 22 is for SSH, and ports 5801 and 5901 are for the VNC remote desktop. To find the internal IP address of your Linux system, type ifconfig in a Linux root shell.

Posted in Uncategorized | Leave a comment

Installing and setting TFTPD in Ubuntu

Installing and setting TFTPD in Ubuntu

1. Install tftpd and related packages.
$ sudo apt-get install xinetd tftpd tftp
2. Create /etc/xinetd.d/tftp and put this entry:

service tftp
{
protocol = udp
port = 69
socket_type = dgram
wait = yes
user = nobody
server = /usr/sbin/in.tftpd
server_args = /tftpboot
disable = no
}

3. Make /tftpboot directory

$ sudo mkdir /tftpboot
$ sudo chmod -R 777 /tftpboot
$ sudo chown -R nobody /tftpboot

4. Start tftpd through xinetd

$ sudo /etc/init.d/xinetd start

Posted in Uncategorized | Leave a comment

GPIO Device driver

GPIO Device driver

Device node creation without using “mknod”
In my last post, where i showed how to write a character gpio driver, i had used mknod for device node creation. Without mknod the device files would not have been created under /dev. So, we had to manually create the device node under /dev using mknod. Now, cannot this manual work be done away with? Of course, it can be done!!.
The automatic creation of device files can be handled with udev. One has to ensure that the major and minor numbers assigned to a device controlled by the driver are exported to user space through the sysfs interface. To know more about this, read “The Linux Device Module” chapter from the Linux Device Drivers book.
Below i am posting the source code for the driver module, the user space application and the Makefile. The user space application and Makefile remain the same. I have only changed the name of the device node under /dev from gpio to gpio_drv. So, the user space application code accordingly reflects this.
The Driver Module:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
 
#define GPIO_NUMBER    149     //any valid gpio number
 
static dev_t first;         // Global variable for the first device number
static struct cdev c_dev;     // Global variable for the character device structure
static struct class *cl;     // Global variable for the device class
 
static int init_result;
 
static ssize_t gpio_read( struct file* F, char *buf, size_t count, loff_t *f_pos )
{
    char buffer[10];
 
    int temp = gpio_get_value(GPIO_NUMBER);
 
    sprintf( buffer, “%1d” , temp );
 
    count = sizeof( buffer );
 
    if( copy_to_user( buf, buffer, count ) )
    {
        return -EFAULT;
    }
 
    if( *f_pos == 0 )
    {
        *f_pos += 1;
        return 1;
    }
    else
    {
        return 0;
    }
}
 
static ssize_t gpio_write( struct file* F, const char *buf, size_t count, loff_t *f_pos )
{
 
    printk(KERN_INFO “Executing WRITE.\n”);
 
    switch( buf[0] )
    {
        case ’0′:
        gpio_set_value(GPIO_NUMBER, 0);
        break;
 
        case ’1′:
        gpio_set_value(GPIO_NUMBER, 1);
        break;
 
        default:
        printk(“Wrong option.\n”);
        break;
    }
    return count;
}
 
static int gpio_open( struct inode *inode, struct file *file )
{
    return 0;
}
 
static int gpio_close( struct inode *inode, struct file *file )
{
    return 0;
}
 
static struct file_operations FileOps =
{
    .owner        = THIS_MODULE,
    .open         = gpio_open,
    .read         = gpio_read,
    .write        = gpio_write,
    .release      = gpio_close,
};
 
static int init_gpio(void)
{
    //init_result = register_chrdev( 0, “gpio”, &FileOps );
 
    init_result = alloc_chrdev_region( &first, 0, 1, “gpio_drv” );
 
    if( 0 > init_result )
    {
        printk( KERN_ALERT “Device Registration failed\n” );
        return -1;
    }
    //else
    //{
    //    printk( KERN_ALERT “Major number is: %d\n”,init_result );
    //    return 0;
    //}
 
    if ( (cl = class_create( THIS_MODULE, “chardev” ) ) == NULL )
    {
        printk( KERN_ALERT “Class creation failed\n” );
        unregister_chrdev_region( first, 1 );
        return -1;
    }
 
    if( device_create( cl, NULL, first, NULL, “gpio_drv” ) == NULL )
    {
        printk( KERN_ALERT “Device creation failed\n” );
        class_destroy(cl);
        unregister_chrdev_region( first, 1 );
        return -1;
    }
 
    cdev_init( &c_dev, &FileOps );
 
    if( cdev_add( &c_dev, first, 1 ) == -1)
    {
        printk( KERN_ALERT “Device addition failed\n” );
        device_destroy( cl, first );
        class_destroy( cl );
        unregister_chrdev_region( first, 1 );
        return -1;
    }
 
    return 0;
}
 
void cleanup_gpio(void)
{
    //unregister_chrdev( init_result, “gpio” );
 
    cdev_del( &c_dev );
    device_destroy( cl, first );
    class_destroy( cl );
    unregister_chrdev_region( first, 1 );
 
    printk(KERN_ALERT “Device unregistered\n”);
}
 
module_init(init_gpio);
module_exit(cleanup_gpio);
 
MODULE_AUTHOR(“Sanchayan”);
MODULE_LICENSE(“GPL”);
MODULE_DESCRIPTION(“Beagleboard-xM GPIO Driver”);
The User Space Application:
#include
#include
 
int main(void)
{
    int fd;
    char gpio_buffer[10];
    char choice[10];
 
    fd = open( “/dev/gpio_drv”, O_RDWR );
 
    printf( “Value of fd is: %d”, fd );
 
    if( fd trigger” in their respective directories.
Now, run the user space application by typing ./gpio_app on the command line prompt. You will be prompted to enter the value “0? or “1? to turn off or turn on the led. You can observe the state of the led pin on your board after this.

Posted in Uncategorized | Leave a comment

Basic board bring up of Olinuxino board & solved libncurses issue.

Built the U-boot successfully through the host and built the kernel and wrote the files in sd card.
There was an issue while configuring menu in linux-sunki folder, the issue was libncurses problem in fedora.
Then I installed libncurses by yum install ncurses-* .
After installing the libncurses i was able to access the menuconfig.

Posted in ARM Embedded Processors, Embedded Linux | Leave a comment

How to Write Your Own Linux Kernel Module with a Simple Example

What are kernel modules?

Kernel modules are piece of code, that can be loaded and unloaded from kernel on demand.

Kernel modules offers an easy way to extend the functionality of the base kernel without having to rebuild or recompile the kernel again. Most of the drivers are implemented as a Linux kernel modules. When those drivers are not needed, we can unload only that specific driver, which will reduce the kernel image size.

The kernel modules will have a .ko extension. On a normal linux system, the kernel modules will reside inside /lib/modules//kernel/ directory.

Earlier we discussed how to compile a kernel from the source.

This tutorial explains how to write a Kernel module using a simple Hello World example.
I. Utilities to Manipulate Kernel Modules
1. lsmod – List Modules that Loaded Already

lsmod command will list modules that are already loaded in the kernel as shown beblow.

# lsmod
Module Size Used by
ppp_deflate 12806 0
zlib_deflate 26445 1 ppp_deflate
bsd_comp 12785 0
..

2. insmod – Insert Module into Kernel

insmod command will insert a new module into the kernel as shown below.

# insmod /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko

# lsmod | grep “squash”
squashfs 35834 0

3. modinfo – Display Module Info

modinfo command will display information about a kernel module as shown below.

# modinfo /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko

filename: /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko
license: GPL
author: Phillip Lougher
description: squashfs 4.0, a compressed read-only filesystem
srcversion: 89B46A0667BD5F2494C4C72
depends:
intree: Y
vermagic: 3.5.0-19-generic SMP mod_unload modversions 686

4. rmmod – Remove Module from Kernel

rmmod command will remove a module from the kernel. You cannot remove a module which is already used by any program.

# rmmod squashfs.ko

5. modprobe – Add or Remove modules from the kernel

modprobe is an intelligent command which will load/unload modules based on the dependency between modules. Refer to modprobe commands for more detailed examples.

II. Write a Simple Hello World Kernel Module

1. Installing the linux headers

You need to install the linux-headers-.. first as shown below. Depending on your distro, use apt-get or yum.

# apt-get install build-essential linux-headers-$(uname -r)

2. Hello World Module Source Code

Next, create the following hello.c module in C programming language.

#include // included for all kernel modules
#include // included for KERN_INFO
#include // included for __init and __exit macros

MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(“Lakshmanan”);
MODULE_DESCRIPTION(“A Simple Hello World module”);

static int __init hello_init(void)
{
printk(KERN_INFO “Hello world!\n”);
return 0; // Non-zero return means that the module couldn’t be loaded.
}

static void __exit hello_cleanup(void)
{
printk(KERN_INFO “Cleaning up module.\n”);
}

module_init(hello_init);
module_exit(hello_cleanup);

Warning: All kernel modules will operate on kernel space, a highly privileged mode. So be careful with what you write in a kernel module.

3. Create Makefile to Compile Kernel Module

The following makefile can be used to compile the above basic hello world kernel module.

obj-m += hello.o

all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

Use the make command to compile hello world kernel module as shown below.

# make

make -C /lib/modules/3.5.0-19-generic/build M=/home/lakshmanan/a modules
make[1]: Entering directory `/usr/src/linux-headers-3.5.0-19-generic’
CC [M] /home/lakshmanan/a/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/lakshmanan/a/hello.mod.o
LD [M] /home/lakshmanan/a/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-3.5.0-19-generic’

The above will create hello.ko file, which is our sample Kernel module.
4. Insert or Remove the Sample Kernel Module

Now that we have our hello.ko file, we can insert this module to the kernel by using insmod command as shown below.

# insmod hello.ko

# dmesg | tail -1
[ 8394.731865] Hello world!

# rmmod hello.ko

# dmesg | tail -1
[ 8707.989819] Cleaning up module.

When a module is inserted into the kernel, the module_init macro will be invoked, which will call the function hello_init. Similarly, when the module is removed with rmmod, module_exit macro will be invoked, which will call the hello_exit. Using dmesg command, we can see the output from the sample Kernel module.

Please note that printk is a function which is defined in kernel, and it behaves similar to the printf in the IO library. Remember that you cannot use any of the library functions from the kernel module.

Posted in Uncategorized | Leave a comment