2

There is a C++ structure having static instance:

class A
{
public:
   A () {}
   
   ~A() {
       // smth.
   }
} a;

Does pkill of process calls destructors of all static objects implemented in C++? Is there a guarentee that pkill, before process termination will call destructor of a?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Martin Ayvazyan
  • 429
  • 1
  • 5
  • 16
  • 2
    Killing a process terminates it immediately, which pretty much guarantees that the process does not get the opportunity to do anything at all. – molbdnilo Mar 17 '23 at 03:57

1 Answers1

1

It depends.

pkill, like kill, sends a signal to the process. By default it sends SIGTERM, but it can send any signal you tell it to.

The default handler for SIGTERM terminates the process immediately, without running object destructors or functions registered with atexit. You can change this behavior by registering your own signal handler using the signal or sigaction functions. If you want to let the rest of your program clean up gracefully, you can have a std::atomic<bool> that the rest of your program periodically checks to determine if it should continue working.

Note that you are fairly limited in what you can safely do in a signal handler. Linux, for example, has a list of async-signal-safe functions that you can safely call. C++17 also specifically specifies that member functions of std::atomic types are safe if the type is lock-free. That means that you should not simply call std::exit directly from a signal handler, since that will execute objects' destructors in the context of the signal handler, which will likely perform unsafe operations.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52