带有线程的 C++ 主程序需要两次 Ctrl+C 才能退出

标签 c++ multithreading pthreads signals

我在 Ubuntu 上运行下面的 C++ 程序,里面有一个线程。
为什么需要调用两次 Ctrl+C 才能退出程序?
我注意到我发出的第一个 Ctrl+C 只会关闭 myThread。

注意:我确定 myThread 线程在第一个 Ctrl+C 后不复存在。这是我通过执行 ps aux 发现的。我得到打印 main_recv_sigint: Executed 只有在第二个 Ctrl+C
在我的生产代码中,我正在执行 python 代码而不是 sleep 1000

我怎样才能让一个 Ctrl+C 完全关闭它?

#include <iostream>
#include <signal.h>
#include <thread>
#include <cstdlib>
#include "unistd.h"
#include <cstdio>

void *myThread(void *params)
{
    std::string cmd = "sleep 1000";
    if (system (cmd.c_str ()));

    return NULL;
}

void main_recv_sigint (int sig);
bool runMainThread = true;

int main(int argc, char *argv[])
{
    pthread_t threadID;
    pthread_create(&threadID, NULL, myThread, NULL);

    signal(SIGINT, main_recv_sigint);

    while (runMainThread) {
        while (runMainThread)
            sleep(2);

        if (!runMainThread)
            break;
    }

    printf("Waiting for myThread() to exit\n");
    pthread_join(threadID, NULL);
    printf("Wait for myThread() exit done\n");

    return 0;
}

void main_recv_sigint (int sig)
{
    printf("main_recv_sigint: Executed\n");
    runMainThread = false;
    return;
}

最佳答案

有两件事可以解释这种行为:

  1. 系统 causes the calling process to ignore SIGINT在等待其 child 终止时
  2. Ctrl-C 向整个前台进程组发送 SIGINT,其中包括您的程序及其子程序 sleep

因此,第一个 Ctrl-C 会终止子 sleep 进程,但会被父进程忽略——永远不会调用处理程序——这继续循环不知不觉。第二个 Ctrl-C 传递一个 SIGINT,它由父级按照您的预期处理。

至于你的第二个问题,“我怎样才能让一个 Ctrl+C 完全关闭它?”,你需要重新设计。 system 是一个旧函数,在设计时没有考虑线程,有点特殊,可能不适合您的用例。

关于带有线程的 C++ 主程序需要两次 Ctrl+C 才能退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32117605/

相关文章:

c++ - 无锁线程池

c - 如何在 Linux 中使用 POSIX pthreads 将整数从文件写入缓冲区?

linux - 在 Linux 中创建远程线程

C++ 迭代器错误 "does not refer to a value"

c++ - 如何将内容追加到 stringstream 类型对象?

java - 同步块(synchronized block)和方法未按预期工作

windows - 将 Windows 手动重置事件移植到 Linux?

C++ 我应该使用指针还是引用?

C++ 一些变量 "used uninitialized in this function"。为什么?

php - 在不退出循环的情况下,将curl_multi_exec限制为3-4个进程,而不是所有进程