 |
 |
Catching Ctrl-C termination in C programs?
|
 |
|
 |
|
Professional Poster
Join Date: Oct 2001
Status:
Offline
|
|
Is there any way that I can execute some code before the a C application quits when sending it Ctrl-C?
|
|
|
| |
|
|
|
 |
|
 |
|
Mac Elite
Join Date: Feb 2000
Location: Nashua NH, USA
Status:
Offline
|
|
should be a sigalam handler right?
|
|
|
| |
|
|
|
 |
|
 |
|
Professional Poster
Join Date: Oct 2001
Status:
Offline
|
|
Originally posted by BLAZE_MkIV:
should be a sigalam handler right?
Ah, don't know what a sigalam handler is, but that pointed me in the right direction. I'm no C programmer (java here), but need to know this, so apparently it's called "signal handling". I found myself a nice tutorial thanks.
|
|
|
| |
|
|
|
 |
|
 |
|
Senior User
Join Date: Nov 2000
Status:
Offline
|
|
I believe you'll find it's SIGINT not SIGALRM.
- proton
|
|
|
| |
|
|
|
 |
|
 |
|
Forum Regular
Join Date: Jan 2001
Status:
Offline
|
|
|
|
|
|
| |
|
|
|
 |
|
 |
|
Dedicated MacNNer
Join Date: Mar 2003
Location: UK
Status:
Offline
|
|
Code:
// Signal handler function.
void handleSignal(int signum) {
switch(signum) {
case SIGHUP:
printf("Caught signal HUP, quitting...");
break;
case SIGQUIT:
printf("Quitting...");
break;
case SIGINT:
printf("Interrupted, quitting...");
break;
default:
printf("Catching signal %i, quitting...", signum);
}
// Shutdown gracefully.
exit(0);
}
// Register signal handlers for common signals.
void registerSignalHandlers() {
signal(SIGHUP, handleSignal);
signal(SIGQUIT, handleSignal);
signal(SIGINT, handleSignal);
signal(SIGABRT, handleSignal);
}
Just call registerSignalHandlers() somewhere at the start of your program, and fill in what you want to do where I've put the printf statements.
|
|
|
| |
|
|
|
 |
|
 |
|
Addicted to MacNN
Join Date: Mar 2000
Location: London, UK
Status:
Offline
|
|
Note that there are very few functions that are safe to call from signal handlers.
|
|
|
| |
|
|
|
 |
|
 |
|
Professional Poster
Join Date: Oct 2001
Status:
Offline
|
|
Thanks everyone for the great help!
|
|
|
| |
|
|
|
 |
 |
|
 |
|
|
|
|
|

|
|
 |
Forum Rules
|
 |
 |
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
 |
 |
 |
 |
|
 |
|