I've recently had a problem with signals. I'd like to write a program in C which would print anything after a signal is sent to the process. For example: If I send SIGTERM to my process (which is simply running program), I want the program to print out for example, "killing the process denied" instead of killing the process. So how to do that? How to force process to catch and change the meaning of such signal. Also I have a question if there is any possibility to kill the init process (I know it's kind of a stupid question, but I was wondering how linux deals with such a signal, and how would it technically look if I type: sudo kill -9 1
.
-
2checkout `sigaction` to intercept SIGTERM or SIGINT, or other signals. – Jean-François Fabre Nov 19 '16 at 20:35
-
2You can't change the meaning of SIGTERM per se; all you can do is change your program's reaction to receiving the signal. There are some signals (SIGKILL and SIGSTOP) that your process (program) cannot do anything about — the process cannot change the default reaction to those signals. – Jonathan Leffler Nov 19 '16 at 20:37
1 Answers
Don't use the signal handler to print. You can set a variable of type volatile sig_atomic_t
instead, and have your main thread check this (see this example).
When your main thread has nothing else to do (which should be most of the time), let it block on a blocking function call (e.g. sleep()
) that will wake up immediately when the signal is received (and set errno
to EINTR
).
C++ gotcha: Unlike the C sleep()
function, std::this_thread::sleep_for()
(in recent versions of glibc) does not wake up when a signal is received.
Regarding if it's possible to kill pid 1, see this question. The answer seems to be no, but I remember that Linux got very grumpy once I booted with init=/bin/bash and later exited this shell – had to hard reboot.
If you're looking for trouble, better kill pid -1.

- 1
- 1

- 5,520
- 4
- 32
- 38
-
A `volatile` might not be sufficient. Either us `_Atomic()` variables or `sig_atomic_t`. – too honest for this site Nov 19 '16 at 21:26
-
-
Given that this is for Linux, not Standard C alone, considerably more things can be done in a signal handler than are allowed in standard C. There's a list of system calls that can be used in [How to avoid using `printf()` in a signal handler](http://stackoverflow.com/questions/16891019/), for example. The list is eclectic on occasion; `write()` is allowed but `strlen()` isn't, officially. There are lots more details in the POSIX standard — at [Signal Concepts](http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04), for example. – Jonathan Leffler Nov 20 '16 at 02:12