【发布时间】:2018-02-11 19:30:51
【问题描述】:
我正在运行以下代码:
// A C program to demonstrate Zombie Process.
// Child becomes Zombie as parent is sleeping
// when child process exits.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Fork returns process id
// in parent process
pid_t child_pid = fork();
// Parent process
if (child_pid > 0)
{printf("in parent process");
sleep(50);
}
// Child process
else
{ printf("in child process");
exit(0);
}
return 0;
}
并得到以下输出:
$main
in child process
我在这里运行代码:http://tpcg.io/6ZccnX
为什么“在父进程中”语句不打印?
【问题讨论】:
-
因为你
sleep(50);。单位是秒,时间长了。改成sleep(1);一切正常。 -
您可能想使用
printf("in parent process\n");,或printf("in parent process"); fflush(stdout);。 -
标准输出的输出通常被缓冲,直到出现换行符。将换行符放在您想要查看的输出的末尾。 (即便如此,如果您将输出通过管道传输到另一个程序或重定向到文件,仅换行符不一定会强制输出;您可能还需要使用
fflush(stdout)— 或者相反,换行符是个好主意一般)。
标签: c process operating-system zombie-process