删除智能指针异步信号是否安全?
让我们的C ++代码已注册信号处理程序。根据 signal-safety(7)所有代码从处理程序中调用,必须使用异步信号安全函数。上面引用的人页面列出了安全的LIBC函数。我试图了解STD :: simelod_ptr ::操作员*是否会满足该要求。
这是一个简单的例子
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准库函数C ++标准允许在信号处理程序中调用C ++标准非常有限,请参见 https://en.cppreference.com/w/cpp/utility/program/signal 。那里没有一个智能指针在那里列出。
Posix对C ++标准库一无所知,因此它也不允许。
因此,没有标准可以保证您是信号安全。我不能对实际实施说什么。
一个问题是您如何创建和访问此
unique_ptr
。请注意,new
ormalloc
均未在任何地方列出为信号安全,如果在信号处理程序中未创建unifer_ptr
,则如何您同步访问它吗?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 neithernew
normalloc
are listed as signal-safe anywhere either and if theunique_ptr
is not created in the signal handler, then how do you synchronize access to it?