Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for exit code to use for custom signal handler?

Tags:

c

linux

signals

I want to add some clean up to the SIGTERM signal. At the same time I have code checking process return code and possible signal exits. Now I have doubts on best practice for signal handling. Which is it?

void handle_sigterm(int sig) 
{ 
    /* cleaning up some stuff */
    /* … */
    /* but what exit code to use? */

    /* maybe 0, because the handler promises more graceful termination than default SIGTERM */
    _exit(0); 

    /* exit code as-if exited by SIGTERM, because that is what initiated termination */
    _exit(128+sig);

    /* similar to above, but leave the details for the default handler */
    signal(SIGTERM, SIG_DFL); /* (not entirely sure this is needed) */
    raise(SIGTERM);
}
like image 929
Andreas Avatar asked Sep 06 '25 18:09

Andreas


1 Answers

The _exit(0) option is wrong; it indicates success. Using _exit(EXIT_FAILURE); might be OK. Dying by reraising the signal allows the parent process to determine unambiguously that the process dies because of the signal. The 128 + SIGTERM convention is used by POSIX (the shell reports the exit status of a process that died as a result of a signal by setting $? to 128 plus the signal number), but it is mildly ambiguous because a process can exit voluntarily with that status, as shown by your code possibly doing so.

If your program is normally invoked by the shell, then any of the non-zero exits is OK, but either of the "128 plus signal number" variants is better. If your program is normally invoked by another process of your own that can usefully distinguish between “definitively died from signal” and “probably died from a signal”, the "reraise the signal" option is probably best, though it is not often used in practice.

like image 132
Jonathan Leffler Avatar answered Sep 08 '25 11:09

Jonathan Leffler