在不使用SA_RESTART的情况下使用sigaction,并防止中篇循环

Using sigaction without SA_RESTART and preventing an infinte loop

本文关键字:循环 情况下 SA RESTART sigaction      更新时间:2024-05-09

我有以下代码:

struct sigaction act = {{0}};
act.sa_handler = handler;
sigaction(SIGINT, &act, nullptr);
while (true) 
{
std::cout << "input:";
std::getline(std::cin, line);
// Handle line
}

当我收到SIGINT时,程序会陷入一个无限循环。我不能简单地设置SA_RESTART(就像这里一样(,因为我想在收到信号时打印一条消息。

我不想直接从处理程序打印,所以我在其中设置了一个标志,并在循环中检查它。

if (flag)
std::count << "got SIGINT" << std::endl;

SA_RESTART导致getline阻塞,所以除非getline返回,否则我无法达到这个if并处理信号。这附近有什么吗?

编辑(完整示例(:

#include <iostream>
#include <signal.h>
bool flag = false;
void handler(int signum)
{
flag = true;
}
int main()
{
struct sigaction act = {{0}};
act.sa_handler = handler;
//act.sa_flags = SA_RESTART;
sigaction(SIGINT, &act, nullptr);
while (true) 
{
std::cout << "input:";
std::string line;
std::getline(std::cin, line);
if (flag) {
std::cout << "got SIGINT" << std::endl;
flag = false;
}
}
}

getline中断时,将在cin上设置错误标志。这需要清除,以防止getline连续出现故障。

if (flag) {
std::cout << "got SIGINT" << std::endl;
flag = false;
std::cin.clear();
}
信号处理程序设置flag时,bool flag = false;不正确。

正确:

std::sig_atomic_t volatile flag = false;

详见std::sig_atomic_t

相关文章: