【发布时间】:2021-03-17 17:34:56
【问题描述】:
在主函数中,我创建了一个连接到 handler 的“sigaction sigact”,并从阻塞中删除了 SIGUSR1 信号sigact.sa_mask 集。 SIGUSR1 是我想从两个孩子那里得到两次的信号,然后再进一步。如何等待两个子进程从中获取 SIGUSR1 信号?
void handler(...){...}
int main()
{
int pipe1[2];
int pipe2[2];
char buf;
struct sigaction sigact;
sigact.sa_handler = handler;
sigfillset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigdelset(&sigact.sa_mask,SIGUSR1);
sigaction(SIGUSR1,&sigact,NULL);
pid = fork();
if(pid == 0){
...
sleep(3); // the sleep is just a must-have of the homework
kill(getppid(),SIGUSR1); // CHILD1
...
}else{
pid1 = fork();
if(pid1 == 0){
...
sleep(3);
kill(getppid(),SIGUSR1); // CHILD2
...
}else{
...
sigsuspend(&sigact.sa_mask); // PARENT
sigsuspend(&sigact.sa_mask); // WAIT FOR SIGUSR1 FROM CHILD1 AND
... // CHILD2 BEFORE GOING FURTHER
... // (The two sigsuspends were my best idea,
... // doesn't work)
// DO OTHER THINGS AFTER TWO SIGNALS CAME
// (e.g. sending children data with pipes,
// just homework stuff...)
}
}
return 0;
}
如您所见,我正在尝试使用两个 sigsuspend,但它们不起作用,它会永远等待。仅使用一个 sigsuspend 即可,但我需要两个孩子的反馈。
如何等待 2 个信号?
【问题讨论】:
-
我认为没有办法做到这一点。考虑使用管道从孩子那里接收。
-
我不能,因为那是大学 xD 的作业,但谢谢@Joshua
-
要允许 SIGUSR1 中断已经运行的 SIGUSR1 处理程序,您必须从处理程序的
sa.sa_mask中清除 SIGUSR1(就像您所做的那样)和还有set theSA_NODEFERflag。 -
作为Linux man pages notes,
sigsuspend通常与sigprocmask结合使用,以暂时取消屏蔽其他被阻塞的信号。想象一下,您在子级中没有sleep(3),但仍希望父级在调用sigsuspend时仅被打断。
标签: c multiprocessing signals parent-child