gpt4 book ai didi

c - 如何多次向 child 发送信号以避免僵尸状态? C语言

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:19 25 4
gpt4 key购买 nike

我需要向子进程发送信号 3 次。

问题是 child 只接收到一次信号,然后就变成了僵尸。

预期的输出是:

我是 child 11385,我收到了 SIGUSR1

我是 child 11385,我收到了 SIGUSR1

我是 child 11385,我收到了 SIGUSR1

但真正的输出是:

我是 child 11385,我收到了 SIGUSR1

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

void my_handler()
{
printf("\n I'm the child %i and i received SIGUSR1\n", getpid());
}


int main (int argc, char **argv) {
int *array;
int N = 10;
int i;
pid_t pid1;
array=(int*)malloc(sizeof(int)*N);


signal(SIGUSR1,my_handler);

for (i = 0; i< N; i++)
{
pid1 = fork();
if(pid1 < 0)
{
exit(EXIT_FAILURE);
}
else if (pid1 > 0)
{
array[i]= pid1;
}

else
{
sleep(100);
exit(EXIT_SUCCESS);
}
}

i=0;
while(i<3) // I need to call the son 3 times
{
kill(array[1], SIGUSR1);
i++;
}
}

最佳答案

当 child 收到信号时,它可能正在等待 sleep 终止。第一个信号会中断 sleep,即使时间还没有到期,导致它返回时 errno 设置为 EINTR。如果你想让它一直休眠,你需要再次调用sleep

关于c - 如何多次向 child 发送信号以避免僵尸状态? C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239160/

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