I need to execute clean up functions in SIGINT handler, but I can't pass local data to it. Here an example:
int main(int argc, char *argv[]) {
struct database *db = db_cursor();
sockfd_t master_socket = init_server();
signal(SIGINT, sigint_handler);
while (1) {
// accepting connections
}
}
void sigint_handler(int s) {
destroy_db(db);
shutdown(master_socket, SHUT_RDWR);
close(master_socket);
exit(EXIT_SUCCESS);
}
How can I implement such behaviour? I've tried make this variables are global, but I can't invoke this functions at compile time (error: initializer element is not a compile-time constant).
Only a very limited number of functions is guaranteed to be async-signal-safe and therefore may be called from within a signal handler,
exit()
f.e. does not belong to them.Take a different approach:
For more on this see
man 7 signal
Note: To be maximal portable you want to use
sigaction()
instead ofsignal()
.The code to replace
signal()
might look like this:Documentation on
sigaction()
: