根据接下来的代码行中 waitpid() 的输出,谁能解释一下为什么子进程处于事件状态?我一直被困在这个问题上。
int main(){
int p;
if (!(p = fork())){sleep(10);
return;}
int s;
sleep(1);
printf("%d \n", waitpid(p,&s, WNOHANG|WUNTRACED));
kill(p,2);
return 0;
}
提前致谢!
最佳答案
评论变成了包含扩展信息的答案。
初始旁白
您的
return;
声明应该是return 0;
并且您的编译器应该提示返回值的函数中没有值的返回。为什么要写扭曲的C?
if ((p = fork()) == 0)
怎么了?作为条件? (不是每个人都会同意我的观点,但你会从我这里得到我的评论,如果其他人选择这样做,他们也可以发表不同的评论。)您应该对系统调用进行错误检查,并打印显着信息(例如 PID,如果
s
报告成功,则打印waitpid()
后waitpid()
中的值,并检查kill()
。请注意,waitpid()
返回除了 child 是否死了(它不会死)之外并没有告诉你太多信息。 sleep (没有死,程序可能会再次醒来 - 除非它先被杀死)和 sleep 之间是有区别的。已经死了(没有机会再次醒来)。waitpid()
函数仅报告已死亡的 child (或未追踪/停止的 child - 此处不是问题),而不报告还活着的 child ,即使他们只是在 sleep 、等待有信号。
你的问题
“子进程处于事件状态”是什么意思?它休眠 10 秒。您的家长代码休眠 1 秒,执行 waitpid()
它立即返回,通常报告没有死去的 child (因为 child 还没有睡完),然后你打断 child (为什么2
不写SIGINT
?)。
你看到了什么;你在期待什么?
waitpid()
returns 0 and I was expecting from it to return the PID of child process. This is what I don't understand. If child process is suspended, why does waitpid() return 0 instead of the PID of child?
POSIX waitpid()
规范说:
Return value
If
wait()
orwaitpid()
returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported. Ifwait()
orwaitpid()
returns due to the delivery of a signal to the calling process, -1 shall be returned anderrno
set to [EINTR]. Ifwaitpid()
was invoked with WNOHANG set inoptions
, it has at least one child process specified bypid
for which status is not available, and status is not available for any process specified bypid
, 0 is returned. Otherwise, -1 shall be returned, anderrno
set to indicate the error.
添加强调
您所看到的完全符合规范。 child 还没有死,所以你无法获得状态,但是因为你使用了WNOHANG
,你得到 0 并立即返回,而不是等到子进程退出。
关于c - 本应处于 sleep 状态的进程处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772751/