Reputation: 11
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
/* A signal handling function that simply prints
a message to standard error. */
void handler(int code) {
fprintf(stderr, "Signal %d caught\n", code);
}
int main() {
// Declare a struct to be used by the sigaction function:
struct sigaction newact;
// Specify that we want the handler function to handle the
// signal:
newact.sa_handler = handler;
// Use default flags:
newact.sa_flags = 0;
// Specify that we don't want any signals to be blocked during
// execution of handler:
sigemptyset(&newact.sa_mask);
// Modify the signal table so that handler is called when
// signal SIGINT is received:
sigaction(SIGINT, &newact, NULL);
// Keep the program executing long enough for users to send
// a signal:
int i = 0;
for (;;) {
if ((i++ % 50000000) == 0) {
fprintf(stderr, ".");
}
}
return 0;
}
When I press ctrl-c, I want my program to print "Signal %d caught\n"
message then exit normally as it would when pressing ctrl-c.
./test ..............................^CSignal 2 caught .................^CSignal 2 caught ..........................................^Z [2]+ Stopped ./test
Right now it just prints the message but doesn't exit the program right after.
Upvotes: 0
Views: 1349
Reputation: 694
That is because the default behavior of ctrl+c
is to exit the program. But by using sigaction()
you are managing the behavior yourself. So if you want the program to end, you can add an exit()
call.
void handler(int code) {
fprintf(stderr, "Signal %d caught\n", code);
exit(code);
}
Upvotes: 1