'Is dereferencing a smart pointer async signal safe?
Let's that my C++ code has registered signal handler. According to signal-safety(7) all code called from within the handler, must use async-signal-safe functions. The man page referenced above lists libc functions that would be safe. I am trying to understand whether std::unique_ptr::operator* would satisfy that requirement.
Here's a simple example
#include <iostream>
#include <csignal>
#include <thread>
#include <chrono>
#include <unistd.h>
class foo
{
public:
foo() { std::cout << "Constructing handler\n";}
~foo() { std::cout << "Destructing handler\n";}
void handle()
{
const char msg[] = "handling\n";
write(STDOUT_FILENO, msg, sizeof(msg));
}
};
bool sig(false);
std::unique_ptr<foo> sig_handler(new foo);
void handler(int)
{
sig = true;
sig_handler->handle();
}
int main()
{
std::signal(SIGINT, handler);
std::cout << "Starting\n";
while (!sig)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Ending\n";
sig_handler.reset();
return 0;
}
Solution 1:[1]
The standard library functions the C++ standard allows to be called in a signal handler are pretty limited, see https://en.cppreference.com/w/cpp/utility/program/signal. None of the smart pointers are listed there.
And POSIX doesn't know anything about the C++ standard library, so it won't allow it either.
So, none of the standards will guarantee you that it is signal-safe. I can't say anything about actual implementations.
A question would be how you are creating and accessing this unique_ptr
. Note that neither new
nor malloc
are listed as signal-safe anywhere either and if the unique_ptr
is not created in the signal handler, then how do you synchronize access to it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |