use*_*879 1 unix linux fork process
我正在 fork 上尝试一些简单的代码。当我给出这样的代码时,它工作得很好。它将打印
我就是孩子
我是家长
然后等待30秒。我知道这是由于这两个进程之间的切换造成的。第一个孩子执行,然后是父母,然后是孩子......
#include<stdio.h>
#include<stdlib.h>
main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("\nI am the child\n");
sleep(30);
exit(0);
}
if(pid>0)
{
printf("\nI am the parent\n");
wait();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我给予喜欢时(无需父母等待)
#include<stdio.h>
#include<stdlib.h>
main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("\nI am the child\n");
sleep(30);
exit(0);
}
if(pid>0)
{
printf("\nI am the parent\n");
}
}
Run Code Online (Sandbox Code Playgroud)
它只是打印
我就是孩子
我是家长
并退出(无需等待 30 秒)。
那么是因为没有等待调用父进程退出而子进程仍在执行吗?但为什么它没有出现在终端(等待)?
父母在这里会变成僵尸吗?
你的观察是正确的。
终端等待原始进程(即父进程)退出。它不等待任何子进程退出。
僵尸进程:如果进程已退出但其父进程未对其调用 wait(),则该进程为僵尸进程。
在你的情况下,父进程不会变成僵尸,因为终端正在等待它。
| 归档时间: |
|
| 查看次数: |
6522 次 |
| 最近记录: |