Originally Posted by
Matticus
Perhaps you should consider using a
state machine.
It could be structured something like this:
Code:
case STATE_0
wait for signal
if signal is what you expect, move to STATE_1
case STATE_1
wait for signal
if signal is what you expect, move to STATE_2
else, move to STATE_0
// ...etc
Awesome! I took your advice and this is what I came up with (seems to be working perfectly!!!!):
Code:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
sig_atomic_t sigusr1_count = 0;
sig_atomic_t sigusr2_count = 0;
typedef enum
{
state1=0,
state2,
state3,
state4
} my_state_t;
my_state_t state = state1;
void do_sleep(int i)
{
while(i)
{
i=sleep(i);
}
}
void handler(int signal_number)
{
if(signal_number == SIGUSR1)
{
++sigusr1_count;
}
if(signal_number == SIGUSR2)
{
++sigusr2_count;
}
switch(state)
{
case state1:
if(signal_number == SIGUSR1)
state = state2;
break;
case state2:
if(signal_number == SIGUSR2)
state = state3;
else
state = state1;
break;
case state3:
if(signal_number == SIGUSR1)
state = state4;
else
state = state1;
break;
case state4:
if(signal_number == SIGUSR2)
exit(1);
else
state = state1;
break;
default:
printf("Invalid signal");
}
}
int main()
{
struct sigaction sa;
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &handler;
sigaction (SIGUSR1, &sa, NULL);
sigaction (SIGUSR2, &sa, NULL);
printf("going to sleep, ima %i\n", getpid());
do_sleep(30);
printf("SIGUSR1 was raised %d times\n", sigusr1_count);
printf("SIGUSR2 was raised %d times\n", sigusr2_count);
return 0;
}