Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent id in fork() and early termination

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

enter image description here

like image 538
snr Avatar asked Dec 31 '25 10:12

snr


1 Answers

Your output is non deterministic since it depends on the OS scheduler. Your parents are exiting after fork faster than child starts hence they get 1 as a parent.

See this two answers for some additional details:

  1. https://stackoverflow.com/a/395883/8199273
  2. https://stackoverflow.com/a/23697850/8199273
like image 105
tgregory Avatar answered Jan 03 '26 05:01

tgregory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!