blob: 8e6bada8928cfaf2b4d561457d38811814c5cca1 [file] [log] [blame]
Jeff King4a16d072009-01-22 01:02:35 -05001#ifndef SIGCHAIN_H
2#define SIGCHAIN_H
3
Heba Walyc0be43f2019-11-17 21:04:50 +00004/**
5 * Code often wants to set a signal handler to clean up temporary files or
6 * other work-in-progress when we die unexpectedly. For multiple pieces of
7 * code to do this without conflicting, each piece of code must remember
8 * the old value of the handler and restore it either when:
9 *
10 * 1. The work-in-progress is finished, and the handler is no longer
11 * necessary. The handler should revert to the original behavior
12 * (either another handler, SIG_DFL, or SIG_IGN).
13 *
14 * 2. The signal is received. We should then do our cleanup, then chain
15 * to the next handler (or die if it is SIG_DFL).
16 *
17 * Sigchain is a tiny library for keeping a stack of handlers. Your handler
18 * and installation code should look something like:
19 *
20 * ------------------------------------------
21 * void clean_foo_on_signal(int sig)
22 * {
23 * clean_foo();
24 * sigchain_pop(sig);
25 * raise(sig);
26 * }
27 *
28 * void other_func()
29 * {
30 * sigchain_push_common(clean_foo_on_signal);
31 * mess_up_foo();
32 * clean_foo();
33 * }
34 * ------------------------------------------
35 *
36 */
37
38/**
39 * Handlers are given the typedef of sigchain_fun. This is the same type
40 * that is given to signal() or sigaction(). It is perfectly reasonable to
41 * push SIG_DFL or SIG_IGN onto the stack.
42 */
Jeff King4a16d072009-01-22 01:02:35 -050043typedef void (*sigchain_fun)(int);
44
Heba Walyc0be43f2019-11-17 21:04:50 +000045/* You can sigchain_push and sigchain_pop individual signals. */
Jeff King4a16d072009-01-22 01:02:35 -050046int sigchain_push(int sig, sigchain_fun f);
47int sigchain_pop(int sig);
48
Heba Walyc0be43f2019-11-17 21:04:50 +000049/**
50 * push the handler onto the stack for the common signals:
51 * SIGINT, SIGHUP, SIGTERM, SIGQUIT and SIGPIPE.
52 */
Jeff King57b235a2009-01-22 01:03:08 -050053void sigchain_push_common(sigchain_fun f);
Heba Walyc0be43f2019-11-17 21:04:50 +000054
Stefan Bellerbfb6b532015-12-15 16:04:09 -080055void sigchain_pop_common(void);
Jeff King57b235a2009-01-22 01:03:08 -050056
Jeff King4a16d072009-01-22 01:02:35 -050057#endif /* SIGCHAIN_H */