我正在尝试使用 fork 系统调用创建一个进程,然后等待子进程。我使用了以下内容:
waitpid (pid, &status, 0);
1)第一个问题是status向左移了8位,例如子进程返回1,waitpid函数返回status变量中status的值为256,请告知原因它正在这样做。
2)根据手册,waitpid等待子进程改变状态。但它也说:
“wait() 系统调用挂起调用进程的执行,直到 它的一个 child 终止。调用 wait(&status) 是等价的 到:
waitpid(-1, &status, 0);"
我在这里有点困惑 waitpid 和 wait 调用是等待状态改变还是等待子进程终止。请澄清这一点。
第三个参数中的零指定了什么?
3) 如果我将子进程置于 sleep 状态,子进程的状态是否会通过等待例如 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);
谢谢
最佳答案
status
参数编码的不仅仅是 child 的退出代码。来自 man waitpid
:
WIFEXITED(status)
returns true if the child terminated normally, that is, by callingexit(3)
or_exit(2)
, or by returning frommain()
.
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call toexit(3)
or_exit(2)
or as the argument for areturn
statement inmain()
. This macro should only be employed ifWIFEXITED
returned true.
main waitpid
解释了第三个参数的作用。
The value of options is an OR of zero or more of the following constants:
WNOHANG
return immediately if no child has exited.
WUNTRACED
also return if a child has stopped (but not traced viaptrace(2)
). Status for traced children which have stopped is provided even if this option is not specified.
WCONTINUED
(since Linux 2.6.10)
also return if a stopped child has been resumed by delivery ofSIGCONT
.
状态变化的定义非常精确和狭义。来自 man waitpid
:
A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal.
休眠不是状态改变。被 SIGSTOP
/SIGTSTP
停止。
关于linux - 进程等待使用linux系统调用wait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416580/