Curious
Curious

Reputation: 494

Sending signals between parent and child process

i am trying to send a user defined (SIGUSR1 or SIGUSR2) signal from parrent process to child process. After child process takes the signal, it waits for 5 seconds and sends another user defined signal to parrent process. When parrent process takes the signal, it writes a string to the screen. I cant figure it out how to do that. I am trying to do that on linux terminal. Here is my code:

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


void wait_function(int signal_1)
{
    signal(SIGUSR1,wait_function);

    if(signal_1==SIGUSR1)
    {
        sleep(5);
    }
}


void writeSomethingOnScreen(int signal_2)
{
    signal(SIGUSR2,createAndWrite);

    if(signal_2==SIGUSR2)
    {
    printf("Hello Stackoverflow!");
    }
}


main()
{
    pid_t pid;
    pid=fork();

    if(pid==0)/*child*/
    {
        signal(SIGUSR1,wait_function);
        pause();
        kill(getppid(),SIGUSR2);
        exit(254);
    }

    if(pid>0)/*parent*/
    {
        signal(SIGUSR2,writeSomethingOnScreen);
        kill(pid,SIGUSR1);
    }
}

Upvotes: 0

Views: 4234

Answers (1)

cnicutar
cnicutar

Reputation: 182609

You are committing many signal no-nos in your program. The most insidious problem that I see is one of racing. There is a window of opportunity between the time you fork and the time you register a signal handler for the child during which a SIGUSR1 can be sent and lost.

Looking at your specific code, imagine a situation where you fork, the parent gets the first chance to run, sends SIGUSR1 to the child before the child ever established a handler and this signal is lost forever. The simplest way to solve this problem is to establish the SIGUSR1 signal handler before forking.

Other problems in your code:

  • The parent process exits long before it has a chance to receive the signal from the child. That is, the parent doesn't just wait around for its children
  • Sleeping in a signal handler is something that sets off most Unix programmers. A signal handler should be as short-lived and as simple as possible
  • I see no reason why you reestablish signal handlers inside the signal handlers - if you want "persistent" handlers use sigaction
  • It is not technically safe to call printf from a signal handler

Upvotes: 1

Related Questions