我需要向子进程发送信号 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
。
我是一名优秀的程序员,十分优秀!