fork() and parent/child process ids

2019-06-14 10:10发布

I am a bit confused about why the child process in the following two programs is showing different parents ids.

First program:

 int main ( void ) {
   int pid, fpid, ppid;
   fpid = fork ();
   pid = getpid();
   ppid = getppid();
   printf ("fpid is %d\n", fpid);
   sleep(5);
   if (fpid > 0){
       printf ("\nThis is Parent. My pid %d. My parent's pid %d\n",pid,ppid);
   }
   else if (fpid ==0){
       sleep(1);
       printf ("\nThis is Child. My pid %d. My parent's pid %d\n",pid,ppid);
   }
   else
       printf ("fork failed\n");
   return (0);
}

Output:

fpid is 53560
fpid is 0

This is Parent. My pid 53559. My parent's pid 44632

MacBook-Pro:~/Desktop/$ 

This is Child. My pid 53560. My parent's pid 53559

Second program:

int main ( void ) {
   int pid, fpid, ppid;
   fpid = fork ();
   printf ("fpid is is %d\n", fpid);
   sleep(5);
   if (fpid > 0){
       pid = getpid();
       ppid = getppid();
       printf ("\nThis is Parent. My pid %d. My parent's pid %d\n",pid,ppid);
   }
   else if (fpid ==0){
       sleep(1);
       pid = getpid();
       ppid = getppid();
       printf ("\nThis is Child. My pid %d. My parent's pid %d\n",pid,ppid);
   }
   else
       printf ("fork failed\n");
   return (0);
}

Output:

fpid is is 53635
fpid is is 0

This is Parent. My pid 53634. My parent's pid 44632

MacBook-Pro:~/Desktop$ 

This is Child. My pid 53635. My parent's pid 1

I understand that process 1 is the process that takes over as a parent once the original parent terminates. I guess what I want to know is: isn't the parent process being finished before the child process can process its printf in both cases? Shouldn't the outputs be the same?

2条回答
可以哭但决不认输i
2楼-- · 2019-06-14 10:52

Since parent and child processes run concurrently, the order of execution depends on runtime. One of them can finish earlier. When parent finishes before child reaches its getppid(), child process would be adopted by init. Hence the parent id 1.
To see child's actual parent process id:

  1. Let the parent wait for its child termination using wait() or waitpid(), or
  2. Let parent sleep for some perceivable amount like sleep(120) after 'This is parent' printf().
查看更多
乱世女痞
3楼-- · 2019-06-14 10:53

isn't the parent process being finished before the child process can process it's printf in both cases?

Very likely so, but not absolutely certain. You cannot ensure that by sleep()ing for any length of time.

Shouldn't the outputs be the same?

They could be the same, but they are unlikely to be. It's important to note when in each program getppid() is called. The parent process ID reported is the one that applied at the time of the call; it is not necessarily still applicable later, when the value is printed.

查看更多
登录 后发表回答