The best way to exit the program gracefully without using pkill

I am currently using a script to call pkillto terminate my C ++ program. However, I noticed that destructors were not called from my traces when using pkill.

Is there another good way that I can exit the program gracefully?
pkillseems messy, and some logs in the buffer are not written. I would like to be able to flush on my fstream and to shut down all resources programatically (instead of relying on O / S to clear my mess).

The application runs 24 hours a day without any problems, the only time I want to stop it is the maintenance time. The application does not have a user interface for entering the type of output.

+5
source share
4 answers

You do this by defining a signal handler for SIGTERMalong these lines:

Somewhere in your include block:

#include <signal.h>
#include <stdio.h>

Yes, we do style me C!

Somewhere regarding the initialization of your code:

signal (SIGTERM, handler);

and then define the code for the signal handlers (clear everything, etc.):

void handler(int num) 
{
  // we might use this handler for many signals
  switch (num)
  {
    case SIGTERM:
      // clean up code.
      break;
  }
}

Now, when you run pkill <app>where <app>is the name of the executable file, the code for will be run handler().

Without switches SIGTERM, a default signal will be sent to the application . If you decide to use a different signal, you will need to make sure that you are sending the same signal as "catch" in handler().

Relevant information can be found on man 7 signaland of course man kill.

+4
source

, .

:

int main()
{
   MyClass a;
   while ( true )
   {
   }
}

. , .

- :

int main()
{
   MyClass a;
   while ( !killSignalReceived() )
   {
   }
}
+4

Zrvan answer, , . signal (7) man page Posix , , , . , printf malloc . ( , ).

Glibc, volatile sig_atomic_t, [s] .

, , . (, select (2) poll (2 ) pselect ppoll) .

, libevent. HTTP-, ​​ onion Wt. SNMP D-bus.

The trick to overcoming the limitations of signal handlers is to pipe them into the same process as, for example, Qt doc . Then the event loop will process the read on this channel.

If your application is multithreaded, signal processing is more complex. Some signals are transmitted in a separate stream.

+4
source

The best way is to process the signal in the program, and then send this signal using kill. In the signal handler, check the flag that will end the main loop.

+3
source

All Articles