c - 调用 SIGINT 时终止线程 - C

标签 c linux multithreading signals posix

我正在构建一个用 C-UNIX 编写的通用程序(使用 Linux,所以我不关心 BSD 或 WIN 函数),它创建两个线程来处理与服务器的通信。

void init_threads(int socket_desc) {

    pthread_t chat_threads[2];

    ret = pthread_create(&chat_threads[0], NULL, receiveMessage, (void*)(long)socket_desc);
    PTHREAD_ERROR_HELPER(ret, "Errore creazione thread ricezione messaggi");

    ret = pthread_create(&chat_threads[1], NULL, sendMessage, (void*)(long)socket_desc);
    PTHREAD_ERROR_HELPER(ret, "Errore creazione thread invio messaggi");

}

由于该程序将从 shell 启动,因此我想实现 CTRL-C 的可能性,因此我使用了这行代码:

signal(SIGINT,kill_handler);
// and its related function
void kill_handler() {
        // retrive threads_id
        // call pthread_exit on the two threads
        printf("Exit from program cause ctrl-c, bye bye\n");
        exit(EXIT_SUCCESS);
      }

我的问题是如何找到事件处理函数内的线程 ID,调用 pthread_exit 是否正确,或者我应该使用其他方法吗?

最佳答案

不要从信号处理程序中调用pthread_exit()!不需要异步信号安全,请参阅signal-safety .

一般来说,您应该在信号处理程序中尽可能少地执行操作。常见的习惯用法是设置一个在主循环中定期检查的标志,例如

volatile sig_atomic_t exitRequested = 0;

void signal_handler(int signum)
{
    exitRequested = 1;
}

int main(void)
{
    // init and setup signals

    while (!exitRequested)
    {
        // do work
    }

    // cleanup
}

此外,请使用 sigaction()用于安装信号处理程序。请参阅signal()出于不使用它的原因。

关于c - 调用 SIGINT 时终止线程 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44629212/

相关文章:

更改 HP Fortify C 规则优先级

创建第二个客户端以发送从服务器接收到的数据

linux - ldconfig - LD_LIBRARY_PATH 不是已知的库类型

Java 线程错误

c# - WPF 在另一个线程上打开新窗口

c - 如何为 ffmpeg amix 过滤器指定多个输入

c - 传递给 execve 的参数会发生什么情况?

linux - 获取linux中每个设备的内存映射

linux - 添加 : colon in the URL

java - 了解 Java 中的多线程