c++ - 如何多次发送SIGINT信号

标签 c++ c multithreading signals interrupt

我正在尝试从其他线程向主线程发送 SIGINT 信号。主线程已经为信号分配了一个处理程序。当我发送第一个信号时,它被处理程序捕获。但我想连续发送信号。但是在处理了第一个信号之后,程序终止了。我放了一个 while 循环。所以我期望它应该继续发送这些信号。以下是我的代码

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

static void catch_function(int signo) {
    puts("Interactive attention signal caught.");
}

DWORD WINAPI MyThreadFunction( LPVOID lpParam ) 
{
    while(1)
    {
        Sleep(50);
        puts("Raising the interactive attention signal.");
        if (raise(SIGINT) != 0) 
        {
            fputs("Error raising the signal.\n", stderr);
            return EXIT_FAILURE;
        }
    }
return 0;
}


int main(void) 
{
     if (signal(SIGINT, catch_function) == SIG_ERR) {
    fputs("An error occurred while setting a signal handler.\n", stderr);
    return EXIT_FAILURE;
    }

    HANDLE thread;
    DWORD  threadId;
    thread = CreateThread(NULL, 0, &MyThreadFunction, NULL, 0, &threadId);
    if(!thread)
    {
        printf("CreateThread() failed");
    }

    while(1)
    {
        Sleep(50);
    }
    puts("Exiting.");
    return 0;
}

下面代码的输出是

Raising the interactive attention signal.
Interactive attention signal caught.
Raising the interactive attention signal.

我也尝试过使用一个简单的例子。在这里,我发送了 3 次信号,但只有第一次信号被捕获。之后程序终止。以下是代码

#include <signal.h>
#include <stdio.h>

void signal_handler(int signal)
{
    printf("Received signal %d\n", signal);
}

int main(void)
{
    // Install a signal handler.
    signal(SIGINT, signal_handler);

    printf("Sending signal %d\n", SIGINT);
    raise(SIGINT);
    raise(SIGINT);
    raise(SIGINT);
    printf("Exit main()\n");
}

输出是

sending signal 2
Received signal 2

所以我想知道如何继续将一些信号从一个线程发送到另一个线程?我希望我的线程之一将发送 SIGINT 信号,而 main 将捕获它们并相应地执行一些操作。

最佳答案

通常在第一个信号之后,信号处理程序被重置为 SIG_DFL(Unix V 信号)和 SIG_INT 的默认行为以退出程序。这就是你所观察到的。因此需要再次重新安装处理程序。在处理程序中再次安装它:

void signal_handler(int signal)
{
    signal(SIGINT, signal_handler);
    printf("Received signal %d\n", signal);
}

更好的方法是使用 sigaction相反,因为它没有这种行为。

关于c++ - 如何多次发送SIGINT信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437568/

相关文章:

c++ - Fstream 正在耗尽我的生命

java - 使用线程从文件中预取有用吗?

python - OpenCV/ python : multi-threading for live facial recognition

java - 正如 Java 之于 Scala,C++ 之于……?

带有 C 接口(interface)的 C++ 库

php - 在多线程之前在长时间运行的后台 shell 脚本中传递数组

C++模板继承看不到基类成员

c++ - 为什么 vector 被认为是 nothrow_move_constructible?

c++ - 如何将多个图标添加到单个 TreeView 项目?

条件编译错误与宏