问题描述
我对以下两个程序中的子进程为什么显示不同的父代id感到困惑。
I am a bit confused about why the child process in the following two programs is showing different parents ids.
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);
}
输出:
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);
}
输出:
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是接管流程原始父级终止后,其父级会终止。我想我想知道的是:在两种情况下,子进程都不能先完成父进程,然后子进程才能处理其 printf
吗?输出不应该相同吗?
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?
推荐答案
由于父进程和子进程同时运行,因此执行顺序取决于运行时。其中之一可以提前完成。当父项在子项到达其 getppid()
之前完成时,子进程将由 init
采用。因此,父ID为1。
要查看孩子的实际父进程ID:
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:
- 让父级等待其子级使用
wait()
或waitpid()
或 - 父级终止在这是父母
printf()
之后,以一些可感知的量睡眠,例如sleep(120)
。
- Let the parent wait for its child termination using
wait()
orwaitpid()
, or - Let parent sleep for some perceivable amount like
sleep(120)
after 'This is parent'printf()
.
这篇关于fork()和父/子进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!