Thursday, December 2, 2010

fork() System Call

System call fork() is used to create processes, the newly created process will be the child of the calling process parent. Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.

fork() returns a process ID AKA PID, there are three instances;

  1. if PID < 0, fork() returns a negative value, the creation of a child process was unsuccessful.


  2. if PID ==0, fork() returns a zero to the newly created child process.


  3. if PID > 0, fork() returns a positive value, the process ID of the child process, to the parent.


After a successful call of fork(),unix makes two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call.



Since both processes have identical but separate address spaces;
  • Variables initialized before the fork() call have the same values in both address spaces.
  • Modifications done in each process will be independent.
Example
#include <signal.h>
#include <stdio.h>

void main() 
{
 int pid;

 printf("Parent process ID %d \n",getpid());

 pid = fork();

  if (pid==0) {
   printf("Child process ID %d \n",getpid());
    int x;
    printf("Enter Value : ");
    scanf("%d",&x);
    printf("Entered Value : %d",x);
  } else if (pid > 0) {
   sleep(5);// parent stops execution for 5 seconds
   printf("Parent process ID %d \n",getpid());

  }

}

3 comments :

  1. A good and very valuble post......got a something in ur post.....thanx(if u can remove the word verification then will be easy to do comment)

    ReplyDelete