简体   繁体   English

从父母向特定孩子发送信号

[英]Send signal from parent to specific child from

I have a tree process with a parent and two child, and I want to send a signal and only the child2 receive it, making a handler for child2 and show a message when he receive it in the handler. 我有一个有一个父母和两个孩子的树进程,我想发送一个信号,只有child2接收它,为child2做一个处理程序,并在处理程序中接收到它时显示一条消息。

pid_t pid, pid1, pid2;

if((pid=fork())==0)
printf("child1");
 else if((pid2=fork())=0)
   printf("child2);
   signal(SIGUSR1, handler); //EDITED
   else
     printf("parent");
     kill(pid2, SIGUSR1); //EDITED


void handler(int signal)
{
  printf("received");

but I dont know how to send signal SIGUSR1 only for child2 但我不知道如何只为child2发送信号SIGUSR1

Assuming that the indentation of your pseudo code represents the nesting depth, it is now correct in principle, but it suffers from timing problems: 假设您的伪代码的缩进表示嵌套深度,则现在原则上是正确的,但存在时序问题:

  • The parent could send the signal to child2 before child2 has installed the signal handler. 父级可以在child2安装信号处理程序之前将信号发送给child2。 To remedy this, you can let the parent install the handler (which is inherited by the child) before forking child2. 为了解决这个问题,您可以让父级在派生child2之前安装处理程序(由子级继承)。
  • child2 could end before the parent gets to send the signal, so the handler wouldn't be invoked. child2可以在父级发送信号之前结束,因此不会调用该处理程序。 If you want to see it invoked, you can give child2 something to do, even if it's only a sleep(…) . 如果您希望看到它被调用,则可以给child2做些事情,即使它只是一个sleep(…)

I hope this is a pseudocode of your actual problem. 我希望这是您实际问题的伪代码。 In that case the problem is that the parent needs to wait till the child has actually installed the handler. 在这种情况下,问题在于父母需要等到孩子实际安装了处理程序。 This can be achieved by making the parent wait till the child signals it("Telling Hi i am up and ready to go"). 这可以通过让父母等到孩子发信号来实现(“告诉我,我已经准备好出发了”)。

have a flag in the parent code as bChildUp. 在父代码中有一个标记为bChildUp。 and wait as 并等待

while (!bChildUp)
{
// do nothing till the child is up.
}

send a signal from child2 to parent process. 从child2向父进程发送信号。 The parent process on receiving the signal can change the bChildUp= TRUE. 接收信号的父进程可以将bChildUp = TRUE更改。 The parent will exit the wait and your task can go on(However you can check if the signal is really from the child2 by getting the pid of the process which sent the signal using siginfo_t and using sigaction to register the signal). 父级将退出等待,您的任务可以继续(但是您可以通过使用siginfo_t获取发送信号的进程的pid并使用sigaction来注册信号来检查信号是否确实来自child2)。

These kind of problems are encountered by 这些问题是由

  1. having a file which the child creates and the parent comes to know that the child is successfully created. 拥有孩子创建的文件,父母知道孩子已成功创建。
  2. Or based on signalling mechanism. 或基于信令机制。

I Would suggest to just create a file in the child2 after it is up and let the parent process wait till the file is created. 我建议在启动后在child2中仅创建一个文件,然后让父进程等待文件创建完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM