Sunday, November 6, 2011

More Processes in C Under Linux

Suppose we want to execute a program on the disk as part of a child process. For this first we should create a child process using fork( ) and then from within the child process we should call an exec function to execute the program on the disk as part of a child process. Note that there is a family of exec library functions, each basically does the same job but with a minor variation. For example, execl( ) function permits us to pass a list of command line arguments to the program to be executed. execv( ) also does the same job as execl( ) except that the command line arguments can be passed to it in the form of an array of pointers to strings. There also exist other variations like execle( ) and execvp( ).
Let us now see a program that uses execl( ) to run a new program in the child process.

# include <unistd.h>
int main( )
{
int pid ;
pid = fork( ) ;
if ( pid == 0 )
{
execl ( "/bin/ls","-al", "/etc", NULL ) ;
printf ( "Child: After exec( )\n") ;
}
else
printf ( "Parent process\n" ) ;
}

After forking a child process we have called the execl( ) function. This function accepts variable number of arguments. The first parameter to execl( ) is the absolute path of the program to be executed. The remaining parameters describe the command line arguments for the program to be executed. The last parameter is an end of argument marker which must always be NULL. Thus in our case the we have called upon the execl( ) function to execute the ls program as shown below

ls -al /etc

As a result, all the contents of the /etc directory are listed on the screen. Note that the printf( ) below the call to execl( ) function is not executed. This is because the exec family functions overwrite the image of the calling process with the code and data of the program that is to be executed. In our case the child process’s memory was overwritten by the code and data of the ls program. Hence the call to printf( ) did not materialize.
It would make little sense in calling execl( ) before fork( ). This is because a child would not get created and execl( ) would simply overwrite the main process itself. As a result, no statement beyond the call to execl( ) would ever get executed. Hence fork( ) and execl( ) usually go hand in hand.

No comments:

Post a Comment