0

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);
    }
}
Curious
  • 474
  • 1
  • 8
  • 25

1 Answers1

1

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
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Reestablishing signal handlers inside the signal handlers was a mistake, i unnoticed that. The printf was just an example, i will make File Processing there. I am new at unix coding, propably your answer is the correct one but i dont know how to do that. Can you send a sample code? – Curious May 05 '14 at 19:19
  • `The printf was just an example, i will make File Processing there.` Looks like a bad Idea: the file processing cannot use any printf() functions, malloc/free (and a few others). Besides it is condidered better design to keep the signalhandlers lightweight: set a flag or write a pipe and return to the original flow. – wildplasser May 05 '14 at 19:23