fork() and parent/child process ids
对于以下两个程序中的子进程为什么显示不同的父代id,我有些困惑。
第一个程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | int main ( void ) { int pid, fpid, ppid; fpid = fork (); pid = getpid(); ppid = getppid(); printf ("fpid is %d\ ", fpid); sleep(5); if (fpid > 0){ printf ("\ This is Parent. My pid %d. My parent's pid %d\ ",pid,ppid); } else if (fpid ==0){ sleep(1); printf ("\ This is Child. My pid %d. My parent's pid %d\ ",pid,ppid); } else printf ("fork failed\ "); return (0); } |
输出:
1 2 3 4 5 6 7 8 | 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 |
第二个程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | int main ( void ) { int pid, fpid, ppid; fpid = fork (); printf ("fpid is is %d\ ", fpid); sleep(5); if (fpid > 0){ pid = getpid(); ppid = getppid(); printf ("\ This is Parent. My pid %d. My parent's pid %d\ ",pid,ppid); } else if (fpid ==0){ sleep(1); pid = getpid(); ppid = getppid(); printf ("\ This is Child. My pid %d. My parent's pid %d\ ",pid,ppid); } else printf ("fork failed\ "); return (0); } |
输出:
1 2 3 4 5 6 7 8 | 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 |
我了解到进程1是原始父级终止后接任父级的进程。我想我想知道的是:在这两种情况下,子进程都不能先完成父进程,然后子进程才能处理其
由于父进程和子进程同时运行,因此执行的顺序取决于运行时。其中之一可以提前完成。当父项在子项到达其
要查看孩子的实际父进程ID:
isn't the parent process being finished before the child process can process it's printf in both cases?
很可能是这样,但不是绝对确定的。您不能通过
Shouldn't the outputs be the same?
它们可能相同,但不太可能相同。重要的是要注意在每个程序中何时调用