Search code examples
cfork

Prompt in terminal prints out before finishing print statements for forks()


I'm very new to fork() processes and in the given code below

#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
int n = 4;
for(i=0; i<n; i++)
   fork();
printf("hello\n");
return 0;
}

prints out something like

cse [prompt] ./Program1
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
cse [prompt] hello
hello
hello
hello
hello
hello

Why exactly does the prompt print out again before finishing printing all the hellos? It doesn't really make sense to me.


Solution

  • save each PID returned by FORK().

    Then use the function waitpid() for each sub process, so the main process does not exit until all the sub processes (the child processes) have exited.