Is there any way to run a function before a program terminates? eg. the user presses ctrl+c and you want to print something to them. Thanks!
Asked
Active
Viewed 220 times
2
-
2Sorry, I should be more specific - this is for Linux – user92489827 Jun 07 '15 at 05:33
1 Answers
3
For *nix systems, you can use the signal()
function.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
volatile sig_atomic_t sig_flag = 0;
void sig_handler(int sig)
{
// A signal has been received. Set `sig_flag` to the value of the signal
sig_flag = sig;
}
int main()
{
// Call sig_handler on SIGINT (Ctrl-C)
signal(SIGINT, sig_handler);
while (sig_flag != SIGINT);
printf("Bye\n");
return 0;
}
EDIT: As per Basile's comment, I should mention that only a select few functions are safe to use under a signal handler, as the handler is called asynchronously. The list of safe functions are available under signal(7)

Levi
- 1,921
- 1
- 14
- 18
-
Yes, but you should mention async signal safe, and perhaps refer explicitly to [signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html) – Basile Starynkevitch Jun 07 '15 at 05:39
-
How would I use this example if I wanted to pass parameters into that function? (without the use of global variables, if pssible) – user92489827 Jun 07 '15 at 05:39
-
1@user92489827: you cannot pass parameters to signals, you need to use global variables. And as I am trying to explain, signal handlers should be *very* simple – Basile Starynkevitch Jun 07 '15 at 05:40
-
BTW, you can't run something *once* a program terminates, but *before* it does (and *after* `SIGINT` has been recieved) – Basile Starynkevitch Jun 07 '15 at 05:41
-
1On Linux specifically, you could also use [signalfd(2)](http://man7.org/linux/man-pages/man2/signalfd.2.html) and poll that descriptor in your event loop – Basile Starynkevitch Jun 07 '15 at 05:42
-
@BasileStarynkevitch I'm trying to keep my answer somewhat generic (see the *nix in the first line of the answer) – Levi Jun 07 '15 at 05:44
-
BTW, `signal` is nearly deprecated. The correct way is to use `sigaction` – Basile Starynkevitch Jun 07 '15 at 05:44