gpt4 book ai didi

c - 本应处于 sleep 状态的进程处于事件状态

转载 作者:行者123 更新时间:2023-11-30 17:23:02 25 4
gpt4 key购买 nike

根据接下来的代码行中 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() or waitpid() 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. If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, -1 shall be returned, and errno set to indicate the error.

添加强调

您所看到的完全符合规范。 child 还没有死,所以你无法获得状态,但是因为你使用了WNOHANG ,你得到 0 并立即返回,而不是等到子进程退出。

关于c - 本应处于 sleep 状态的进程处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com