有人可以给我解释一下等待做什么,exit(0),exit(1),exit(2)等之间有什么区别。
这是我很困惑的代码。
int main()
{
if (fork()== 0)
printf("HC: hello from child\n");
else
{
printf("HP: hello from parent\n");
wait(NULL);
printf("CT: child has terminated\n");
}
printf("Bye\n");
return 0;
}
输出量
HC: hello from child
Bye
HP: hello from parent
CT: child has terminated
(or)
HP: hello from parent
HC: hello from child
CT: child has terminated // this sentence does
// not print before HC
// because of wait.
Bye
这是来自geeksforgeeks的代码,因此转到if语句,如果if语句为true,则执行
printf("HC: hello from child\n");
,但是为什么又返回else语句并打印出printf("HP: hello from parent\n"); printf("CT: child has terminated\n");
?
最佳答案
您正在从单进程的角度看这件事。 fork()
创建另一个与父进程完全相同的进程,只是有一个不同:克隆上fork()
函数调用的结果是0
,但是在父进程上,它是操作产生的PID。
因此,if (fork == 0)
仅对孩子适用。
换句话说,两个分支同时跟随。wait()
部分是父级如何等待子级进程终止的方式。 NULL
作为参数的意思大致是“不在乎哪个孩子,只是在乎哪个孩子”。通常,您将waitpid()
与通过pid
调用获得的fork()
值一起使用,但这仅在可能涉及多个子进程的情况下才非常重要。
如果您不“收获”您的孩子,那么您的进程最终会变成僵尸,因此wait
部分非常重要。
关于c - C中的系统调用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049780/