I'm practising with parallel programming by using fork()
. I expect that parent id of every process is id of former process but in my output shows same id. Why? The second question is about termination. Sometimes the output shows all processes, sometimes just two or three, sometimes only one. Why? I know parent process should wait its children, but what if not as in my question. My confusion is when fork()
is called, both processes are executed without knowledge of their orders, aren't they?, maybe the parent process terminates its own execution. But its child can go on running to rest of program or terminated or something else? (As it can be seen on the output not always termination, not always fully correct neither) I don't comprehend the output showing only one but sometimes two or three or not all. I hope I could explain my problems. Seemingly, I couldn't.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i;
for (i = 0; i < 3; i++)
if (childpid = fork())
break;
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
Output(s):
i:0 process ID:2783 parent ID:1954 child ID:2784
i:1 process ID:2784 parent ID:1 child ID:2785
i:2 process ID:2785 parent ID:1 child ID:2786
i:3 process ID:2786 parent ID:1 child ID:0
or
//how??
i:0 process ID:3016 parent ID:1954 child ID:3017
i:1 process ID:3017 parent ID:1 child ID:3018
i:2 process ID:3018 parent ID:1 child ID:3019
or
//how??
i:0 process ID:4079 parent ID:1954 child ID:4080
i:1 process ID:4080 parent ID:1 child ID:4081
or
//how??
i:0 process ID:3038 parent ID:1954 child ID:3039
Expected output:
i:0 process ID:2783 parent ID:1954 child ID:2784
i:1 process ID:2784 parent ID:2783 child ID:2785
i:2 process ID:2785 parent ID:2784 child ID:2786
i:3 process ID:2786 parent ID:2785 child ID:0