tags:

views:

62

answers:

3

If I have a parent coordinator program and a worker program, but the coordinator program is creating all of the needed worker processes. If I want to implement the alarm() method correctly to kill all of the processes and terminate the program after a certain amount of time.

Is this the correct way to implement it? The current way I have it, it does now print out the message corresponding printf() message for the worker processes being killed.

Note: I implemented the ignoring of interrupt signals so more worker processes could proceed without worry.

int main(int argc, char** argv)
{
signal(SIGINT, sig_ctrl);
signal(SIGALRM, sig_alarm);

alarm(5); 
sleep(10);

    //rest of program which creates the needed processes

}

void sig_ctrl(int sig)
{
printf("Hold on buddy, you're not terminating this program with CTRL^C.\n");
}

void sig_alarm(int sig)
{
sleep(0);
fflush(stdout);
printf("The alarm is sounding, all worker procceses will be...TERMINATED!");
raise(SIGTERM);
 }
+2  A: 

There's the easy way, which is arguably the sloppy way, and the hard way.

The easy way involves ensuring that the initial process is the process group leader, that it ignores an appropriate signal (but that its children do not ignore the signal), and then sending the signal to the process group.

The harder way requires a list somewhere of all the child processes, and the parent can then duly send a signal to each of the processes, removing the dead ones from its list.

Jonathan Leffler
A: 

I had the same type of problem in some homework for a unix unit. That is pretty much the solution most people came up with :P

Craig
+1  A: 

Your program's problem is that sleep() is usually implemented using the SIGALRM timer, so calling it probably overrides your signal() setting for SIGALRM

$ man 3 sleep

BUGS
       sleep()  may be implemented using SIGALRM; mixing calls to alarm(2) and
       sleep() is a bad idea.

(BTW, The sleep(0) is nonsense too. What are you trying to achieve with that?)

martinwguy