Unix – In what manner, fork() system call making child process

cforkunix

Here is my code for fork() system call,

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
int main(int argc, char *argv[])
{
 pid_t pid;
 pid=fork();
 printf("1st Fork\n");
 printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
 pid=fork();
 printf("2nd Fork\n");
 printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
 pid=fork();
 printf("3rd Fork\n");
 printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
 return 0;
}

While running the code, i am getting output like

1st Fork
Process ID : 3393, Parent Process ID : 3392
2nd Fork
Process ID : 3394, Parent Process ID : 3393
3rd Fork
Process ID : 3395, Parent Process ID : 3394
3rd Fork
Process ID : 3394, Parent Process ID : 3393
2nd Fork
Process ID : 3393, Parent Process ID : 3392
3rd Fork
Process ID : 3397, Parent Process ID : 3393
3rd Fork
Process ID : 3393, Parent Process ID : 3392
1st Fork
Process ID : 3392, Parent Process ID : 3440
2nd Fork
Process ID : 3398, Parent Process ID : 3392
3rd Fork
Process ID : 3400, Parent Process ID : 3398
3rd Fork
Process ID : 3398, Parent Process ID : 3392
2nd Fork
Process ID : 3392, Parent Process ID : 3440
3rd Fork
Process ID : 3401, Parent Process ID : 3392
3rd Fork
Process ID : 3392, Parent Process ID : 3440

Why this fork() system call making 8 process and how?

Also i am getting 14 printf() statement executions. Why?

Best Answer

Each time you call fork it returns twice. Once in the parent, once in a new process. Then as they go on, they both fork again.

It's most likely you didn't expect the children to fork again. With each fork you usually have:

switch (fork()) {
case -1:
    /* ERROR. */
    break;
case 0:
    /* Child process. */
    break;
default:
    /* Parent. */
    break;
}

In your code it's like this:

  • You have one process, then it forks
  • You now have two processes and both fork
  • You now have 4 processes and all of them fork
  • You now have 8 processes and you're asking questions on SO
Related Topic