Update
You are missing a set of brackets in the updated code. It should be if ((pid[i] = fork()) == -1) not if (pid[i] = fork() == -1) !
The latter is equivalent to if (pid[i] = (fork() == -1)) due to priority rules. It finishes assigning 0 to pid[i] every time through the loop, so the parents think that they are child processes and do not exit the loop.
I agree with your analysis of what should happen. The parent must give birth to a child and then exit, so each printout i=n should be displayed only once.
Are you sure you typed it exactly as indicated in your question? I launched your program (with minor changes) and got the expected result:
$ cat fork.c #include <unistd.h> #include <stdio.h> #include <stdlib.h> #define N 5 int main() { int pid[N], i; for(i=1;i<N;i++) /* What's the total number of processes? */ { printf("i=%d\n",i); // Output of all the is if((pid[i]=fork())==-1) exit(1); else if(pid[i] > 0) break; } return 0; } $ gcc -o fork fork.c $ ./fork i=1 i=2 $ i=3 i=4
Note that I have moved \n to the printout to the end. When you put it at the beginning of the line, you will get stdout , which will not be cleared, so you will get several printouts when the parent and child processes will clear the output buffers. This may be the cause of your problem. FWIW on my Mac, I received every printout twice.
source share