Martin Ayvazyan
Martin Ayvazyan

Reputation: 499

`pkill` and static objects destruction in C++

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?

Upvotes: 2

Views: 89

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30639

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.

Upvotes: 1

Related Questions