c++ - 为什么 signalhandler 不输出任何东西?

标签 c++ linux signals

#include <iostream>
#include <signal.h>
#include <unistd.h>

using namespace std;

void sighandler(int sig) {
    cout << "signal received" << endl;
}

int main() {

    int pid= getpid();
    cout << pid << endl;

    signal( SIGUSR1, sighandler );

    sigset_t accept;
    sigaddset( &accept, SIGUSR1 );
    int s;

    sigwait(&accept, &s);

    cout << s << endl;

    return 0;
}

当我运行这个程序并通过“kill -s SIGUSR1 $pid”向它发送一个 SIGUSR1 信号时,它只输出信号的编号 (10) 而不是 sighandler 中的文本。我不明白为什么。这是在 Linux 系统上。

最佳答案

来自 sigwait - wait for queued signals

DESCRIPTION

The sigwait() function selects a pending signal from set, atomically clears it from the system's set of pending signals, and returns that signal number in the location referenced by sig.

因此,通过使用 sigwait(),信号已被传送并由您的程序处理。

当您删除 sigwait 调用并进行休眠或忙等待时,SIGUSR1 信号将被传送到您的信号处理程序,消息“收到信号”将被发送打印出来。

关于c++ - 为什么 signalhandler 不输出任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233305/

相关文章:

c++ - 在Windows 7上将原始数据写入硬盘(PhysicalDrive)的最快方法

C++错误: Expected constructor,析构函数,或 '(' token 前的类型转换

linux - 有没有一种方法/工具可以在 Linux 下列出标记为 "thin"的 TCP 连接?

linux - ARM Linux ":start_kernel is not calling after decompressing uImage"

python - celery task_success 与发件人过滤器

multithreading - 通过 POSIX 信号终止 C++11 中的多线程应用程序

c++ - 计算C++中相同运行进程的总数

c++ - 如何使用 vtkStreamTracer 类通过我的非结构化网格数据 (vtu) 生成流线

linux vim 在编辑器中粘贴目录路径

python - 如何诊断 Ctrl + C 不停止 pserve 的原因