"kill -15" runs the sigaction code but does not interrupt my C program

I have a program developed in C. I added a sigaction inorder to this program to execute some C code before exiting 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 routines 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 stdout, but the program is not finished.

Am I missing sigaction in my code?

+3
source share
3 answers

exit() not necessarily safe for an asynchronous signal.

To terminate the process directly from the signal handler, call either _exit() or abort() .


flock() , and all members of the printf function family are also not stored in async-signal.


For a complete list of functions protected against an asynchronous signal, you may like to click here .

+4
source

I still suspect that you have an XY problem that is trying to unflock flock() to get the SIGTERM file.

To achieve this (and bypass this limitation, in order to be able to use only the signal reception functions safe for asynchronous reception, use the following approach:

  • Check all the signals that will be processed by the application in the main thread.
  • Create a thread.
  • Make this stream receive all the signals that need to be processed by modifying the stream signal mask.
  • In this stream loop around sigwaitinfo() to receive and send signals.
  • Then, depending on the signal received by this stream, do what needs to be done without any restrictions due to the lack of an asynchronous signal-saftyness of any function.
+2
source

Most likely, this is due to the fact that in fact you are not allowed to do anything in the signal handler (and the functions of calling the library are, of course, fragmentary).

The usual way to deal with something like this is if the signal handler sets a variable or queues an event that will handle a regular main loop and then exits.

+1
source

Source: https://habr.com/ru/post/946709/


All Articles