Saturday 8 August 2015

Implementation of fork() (Creating child process in Linux)


Program: 

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
pid_t pid;
 //This line prints the pid of the terminal from which the program was executed
 printf("Parent of parent process : %d\n",getppid());
 printf("Parent process id: %d\n",getpid());

pid=fork();
if(pid<0){
 fprintf(stderr,"Fork Failed");
 return 1;
}
//This part of code executed only by child process
else if(pid==0){
 printf("Child's execution starts\n");
 printf("Child procecss id: %d\n",getpid());
 printf("Parent of this child : %d\n",getppid());
}

//This part of code executed only by Parent process
else{ 
        //printf("PID:%d",pid); // This line will print process id of child
 //Parent process waits for the completion of Child
 wait(NULL);
 printf("\nChild ended and Parent process resumes\n");
 
}
printf("Ending statement: This will be excuted by both child and parent");
return 0;
}


Output:
Explanation:

Before going into the explanation of the above program, let's have a look at fork() function-
fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate(Resources limited in some implementations) of the calling process, referred to as the parent.

IMP:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created.

Now in above program, getpid() returns the PID of the calling process, getppid() returns the PID of the parent process, wait() is executed by parent process and stops the parent process until the child process terminates or finishes execution.
The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

Section of code where PID==0 is executed by child process only because fork functions returns 0 only to the child.
and the else part is executed only by the parent because fork returned a value > 0 to the parent which was precisely the process ID of the child.
Now for the last part, since child is an exact duplicate of the parent process last line of code is executed by both the parent and the child (Since exec() call is not used here).

No comments:

Post a Comment