简体   繁体   English

调用SIGINT时终止线程-C

[英]Terminate threads when SIGINT is called - C

I'm building a generic program written in C-UNIX (using Linux so I don't care about BSD or WIN functions), that creates two threads to handle the communication with a server. 我正在构建一个用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");

}

Since this program will be launched from shell I want to implement the CTRL-C possibility and so did I with this line of code: 由于此程序将从外壳启动,因此我想实现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);
      }

My question is how can I found out the thread ids inside the event handler function and is it correct to call pthread_exit or should I use something else? 我的问题是如何找到事件处理程序函数中的线程ID,调用pthread_exit是否正确,还是应该使用其他东西?

Don't call pthread_exit() from a signal handler! 不要从信号处理程序中调用pthread_exit() It is not required to be async-signal-safe , see signal-safety . 不需要是异步信号安全的 ,请参阅signal-safety

In general, you should do as little as possible in a signal handler. 通常,您应该在信号处理程序中执行尽可能少的操作 The common idiom is to just set a flag that is periodically checked in your main loop like eg 常见的用法是设置一个标志,该标志在您的主循环中定期检查,例如

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
}

Also, use sigaction() for installing signal handlers. 另外,使用sigaction()安装信号处理程序。 See signal() for reasons not to use it. 不使用signal()的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM