Reputation: 494
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
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:
sigaction
printf
from a signal handlerUpvotes: 1