Reputation: 99
I wrote this program to catch the Ctrl-C and -\ or sigint
and sigquit
functions, I commented in my understanding of what this program does. Could you correct me if I am wrong and/or maybe explain what is going on so I can have a better understanding?
//
// main.c
// Project 4
//
// Found help with understanding and coding at
// http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/
//
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
//signal handling function that will except ctrl-\ and ctrl-c
void sig_handler(int signo)
{
//looks for ctrl-c which has a value of 2
if (signo == SIGINT)
printf("\nreceived SIGINT\n");
//looks for ctrl-\ which has a value of 9
else if (signo == SIGQUIT)
printf("\nreceived SIGQUIT\n");
}
int main(void)
{
//these if statement catch errors
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
if (signal(SIGQUIT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGQUIT\n");
//Runs the program infinitely so we can continue to input signals
while(1)
sleep(1);
return 0;
}
Upvotes: 2
Views: 735
Reputation: 26647
There is an online tutorial.
SIGINT
is straightfoward to use, but you should use sigaction
rather than signal
.
To catch SIGCHLD
you use the code from the tutorial and you can reap the child status with one of the wait()
functions.
void handle_sigchld(int sig) { int saved_errno = errno; while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {} errno = saved_errno; } struct sigaction sa; sa.sa_handler = &handle_sigchld; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_NOCLDSTOP; if (sigaction(SIGCHLD, &sa, 0) == -1) { perror(0); exit(1); }
Upvotes: 1