Saturday, April 14, 2012

What is fork() in C language?


As we know, our running program is a process. From this process we can create another process. There is a parent-child relationship between the two processes. The way to achieve this is by using a library function called fork( ). This function splits the running process into two processes, the existing one is known as parent and the new process is known as child. Here is a program that demonstrates this…

# include <sys/types.h>
int main( )
{
printf ( "Before Forking\n" ) ;
fork( ) ;
printf ( "After Forking\n" ) ;
}
Here is the output of the program…
Before Forking
After Forking
After Forking

As we know, fork( ) creates a child process and duplicates the code of the parent process in the child process. There onwards the execution of the fork( ) function continues in both the processes. Thus the duplication code inside fork( ) is executed once, whereas the remaining code inside it is executed in both the parent as well as the child process. Hence control would come back from fork( ) twice, even though it is actually called only once. When control returns from fork( ) of the parent process it returns the PID of the child process, whereas when control returns from fork( ) of the child process it always returns a 0. This can be exploited by our program to segregate the code that we want to execute in the parent process from the code that we want to execute in the child process. We have done this in our program using an if statement. In the parent process the ‘else block’ would get executed, whereas in the child process the ‘if block’ would get executed.


# include <sys/types.h>
int main( )
{
int pid ;
pid = fork( ) ;
if ( pid == 0 )
{
printf ( "Child : Hello I am the child process\n" ) ;
printf ( "Child : Child’s PID: %d\n", getpid( ) ) ;
printf ( "Child : Parent’s PID: %d\n”, getppid( ) ) ;
}
else
{
printf ( "Parent : Hello I am the parent process\n" ) ;
printf ( "Parent : Parent’s PID: %d\n”, getpid( ) ) ;
printf ( "Parent : Child’s PID: %d\n", pid ) ;
}
}

No comments:

Post a Comment