Systems Programming :: System Calls For Process Management II

Sunday, April 4, 2010 Posted by Kanishka Dilshan
fork() and wait() system calls

fork() system call
using fork system call we can create new child processes. Though we call fork() once it returns twice! once per processes (at parent process and child process). At parent process it returns PID of the child process. At child process it returns 0. Using this feature we can identify parent and child processes separately.
lets see an example to understand the behaviour of fork() system call
example 1:


 1: #include <stdio.h>
 2: 
 3: int main()
 4: {
 5:  printf("Parent says \t: Parent process started...\n");
 6:  int PID=fork();
 7:  if(PID==0)
 8:  {
 9:   //this code block is executed by the child process
10:   int childPID=getpid();
11:   int parentPID=getppid();
12:   printf("Child says \t: Child PID -> %d \n",  childPID);
13:   printf("Child says \t: My Parent's PID -> %d \n",  parentPID);
14:  }
15:  else
16:  {
17:   //this code block is executed by the parent process (PID!=0)
18:   int parentPID=getpid();
19:   printf("Parent says \t: my Child's PID %d \n",PID);
20:   printf("Parent says \t: my PID -> %d \n",parentPID);
21:  }
22:  
23:  printf("Both say \t: This statement is executed by child and parent \n");
24:  return 0; //end of the program
25: }


output 1:
Labels:

Post a Comment