问题
I have a program developed in C. I added to this program a sigaction handler inorder to execute some C code before quit the program:
void signal_term_handler(int sig)
{
printf("EXIT :TERM signal Received!\n");
int rc = flock(pid_file, LOCK_UN | LOCK_NB);
if(rc) {
char *piderr = "PID file unlock failed!";
fprintf(stderr, "%s\n", piderr);
printf(piderr);
}
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
struct sigaction sigint_action;
sigint_action.sa_handler = &signal_term_handler;
sigemptyset(&sigint_action.sa_mask);
sigint_action.sa_flags = SA_RESETHAND;
sigaction(SIGTERM, &sigint_action, NULL);
...........
}
Note: My program contains 2 subthreads running
When I execute myprogram and then I call kill -15 <pidnumber>
to kill my program. I get the message "EXIT :TERM signal Received!\n
" printed in the stdout but the program is not exited.
Am I missing someting in my sigaction code?
回答1:
exit()
is not necessarily async-signal safe.
To end a process directly from a signal handler call either _exit()
or abort()
.
flock()
and all members of the printf
family of functions aren't async-signal-save either.
For full list of async-signal-safe functions you might like to click here.
回答2:
I still suspect you have an XY-problem, that is trying to un-flock()
a file on receiving SIGTERM
.
To achieve this (and with this get around the limitation to only be able to use async-signal-safe functions on signal reception use the following approach:
- Mask out all signals to be handled by the app in the main thread.
- Create a thread.
- Make this thread receive all signals to be handled, by modifing the thread's signal mask.
- In this thread loop around
sigwaitinfo()
to receive and dispatch signals. - Then depending on the signal received by this thread do what needs to be done without any limitation due to missing async-signal-saftyness of any function.
回答3:
Most likely this is because you aren't really allowed to do much of anything in a signal handler (and calling library functions is certainly sketchy).
The normal way to handle something like this is for the signal handler to set a variable or queue up an event that the normal main loop will handle and then exit.
来源:https://stackoverflow.com/questions/16966353/kill-15-triggers-the-sigaction-code-but-does-not-terminate-my-c-program