简体   繁体   中英

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.

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

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. To remedy this, you can let the parent install the handler (which is inherited by the child) before forking child2.
  • child2 could end before the parent gets to send the signal, so the handler wouldn't be invoked. If you want to see it invoked, you can give child2 something to do, even if it's only a 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. and wait as

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

send a signal from child2 to parent process. The parent process on receiving the signal can change the 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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