I wrote the following code for a school assignment - It compiles and prints all the correct messages. But just for my own curiosity, I would like to know if my code can be shor
I would like single signal handler and a print function with switch-case for each kind of signal message:
volatile sig_atomic_t flag = 0;
// single signal handler
static void sigHandler_sigusr(int sig_no){
flag = sig_no;
}
void print_msg(int message_no){
switch(message_no){
case SIGUSR1: printf("Caught SIGUSR1\n");
break;
case SIGUSR2: printf("Caught SIGUSR2\n");
break;
case SIGINT: printf("Caught SIGINT, Exiting\n");
exit(EXIT_SUCCESS);
default:
printf("Some other signal");
}
}
Now, Check the flag
in your main, and call print_msg(flag)
.
My suggestion: avoid using printf in a signal handler.
In main(), register your single signal handler for each kind of signal.
// prepare struct
struct sigaction sa;
sa.sa_handler = sigHandler_sigusr;
sa.sa_flags = SA_RESTART; // Restart functions if
// interrupted by handler
/* // unComment if you wants to block
// some signals while one is executing.
sigset_t set;
sigemptyset( &set );
sigaddset( &set, SIGUSR1 );
sigaddset( &set, SIGUSR2 );
sigaddset( &set, SIGINT );
sa.sa_mask = set;
*/
// Register signals
sigaction( SIGUSR1, &act, NULL );
sigaction( SIGUSR2, &act, NULL );
sigaction( SIGINT, &act, NULL );
See the sigaction documentation, including an example.
static void sigHandlers(int sig)
{
if (sig == SIGINT)
printf("Caught SIGINT, Existing\n");
else if (sig == SIGUSR1)
printf("Caught SIGUSR1\n");
else //no need to switch since you have only 3 sig
printf("Caught SIGUSR2\n");
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
struct sigaction s[4] = {0};
s[0].sa_handler = sigHandlers;
sigemptyset(&(s[0].sa_mask));
memcpy(&s[1], s, sizeof(struct sigaction));
memcpy(&s[2], s, sizeof(struct sigaction));
sigaction(SIGUSR1, &s[0], &s[3]);
sigaction(SIGUSR2, &s[1], &s[3]);
sigaction(SIGINT, &s[2], &s[3]);
kill(getpid(), SIGUSR1);
kill(getpid(), SIGUSR2);
kill(getpid(), SIGINT);
return 0;
}
But I'm sure you can reduce the code with #define