gpt4 book ai didi

c - 了解子进程终止时的 SIGCHLD

转载 作者:IT王子 更新时间:2023-10-29 00:38:59 28 4
gpt4 key购买 nike

我无法理解以下程序的输出。我观察到子进程返回后,父进程在 wait() 之前没有休眠 3 秒。如果 SIGCHLD 设置为默认处理程序,则它会休眠 3 秒,调用等待并按预期返回。这里究竟发生了什么??

# include <unistd.h>
# include <sys/types.h>
# include <stdio.h>
# include <sys/wait.h>
# include <signal.h>

void handler(int sig) {
printf("Iam in handler ...\n");
}

main() {

int status;
pid_t pid;

struct sigaction act;
//act.sa_flags=SA_NOCLDSTOP;
act.sa_handler=handler;
sigaction(SIGCHLD,&act,NULL);

if(!fork()) {
printf("child process id is %d\n",getpid());
return 1;
}

printf("xxx ...\n");
sleep(3);
pid = wait(&status);
printf("process terminated is %d\n",pid);

}

output::

xxx ...
child process id is 2445
Iam in handler ...
process terminated is 2445

最佳答案

来自man for sleep() :

sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

你的 child 终止会产生一个信号来唤醒你。

sleep() 的返回值:

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

如果您想帮助您“完成” sleep ,可以使用。

unsigned sleep_time = 3;
...
while((sleep_time = sleep(sleep_time)) > 0) {}
pid = wait(&status);
...

关于c - 了解子进程终止时的 SIGCHLD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14266485/

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