Skip to content

Instantly share code, notes, and snippets.

@m-renaud
Last active December 20, 2015 08:39
Show Gist options
  • Save m-renaud/6101759 to your computer and use it in GitHub Desktop.
Save m-renaud/6101759 to your computer and use it in GitHub Desktop.
signal() and sigaction()
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void signal_handler_function(int signo);
typedef void (*sighandler_t)(int);
int main()
{
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Old: Use of signal()
// Set errno to zero before the call.
errno = 0;
sighandler_t old_sighandler = signal(SIGINT, signal_handler_function); // OR
// signal(SIGINT, &signal_handler_function);
if(old_sighandler == SIG_ERR)
{
fprintf(
stderr,
"signal() failed...\n"
"signum is invalid\n"
);
exit(1);
}
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// New: Use of sigaction()
struct sigaction act;
struct sigaction oldactions;
memset(&act, 0, sizeof(act));
act.sa_handler = signal_handler_function;
sigfillset(&act.sa_mask);
act.sa_flags = 0;
// Set errno to zero before the call.
errno = 0;
int sigaction_return = sigaction(SIGINT, &act, &oldactions);
if (sigaction_return == -1)
{
fprintf(stderr, "sigaction() failed\n");
if (errno == EFAULT)
{
fprintf(stderr, "act or oldact not part of address space\n");
exit(2);
}
else
{
fprintf(stderr, "Invalid signal specified.\n");
exit(3);
}
}
sigaction_return = sigaction(SIGINT, &oldactions, NULL);
return 0;
}
void signal_handler_function(int signo)
{
printf("Handled signal %d.\n", signo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment