【发布时间】:2017-01-01 15:33:15
【问题描述】:
我正在尝试使用 fork 系统调用创建一个进程,然后等待子进程。我使用了以下内容:
waitpid (pid, &status, 0);
1) 第一个问题是状态向左移动了 8 位 例如,如果子进程返回 1,waitpid 函数返回状态变量中状态的值为 256。请告诉我为什么它正在这样做。
2)根据手册,waitpid等待子进程改变状态。但它也说:
"wait() 系统调用暂停调用进程的执行,直到 它的一个孩子终止。调用 wait(&status) 是等价的 到:
waitpid(-1, &status, 0);"
我有点困惑,waitpid 和 wait 调用是等待状态更改还是子进程终止。请澄清这一点。
第三个论证中的零表示什么?
3) 如果我将子进程置于睡眠状态,子进程的状态是否会通过等待例如 5 秒变为等待状态?
以下是我的程序:
int main(int argc, char ** argv)
{
pid_t pid = fork();
pid_t ppp;
if (pid==0)
{
sleep(8);
printf ("\n I am the first child and my id is %d \n", getpid());
printf ("The first child process is now exiting now exiting\n\n");
exit (1);
}
else {
int status = 13;
printf ("\nI am now waiting for the child process %d\n", pid);
waitpid (pid, &status, 0);
printf ("\n the status returned by the exiting child is %d\n", status>>8);
}
printf("\nI am now exiting");
exit(0);
}
谢谢
【问题讨论】:
标签: linux process fork waitpid