Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用SIGINT时终止线程-C_C_Linux_Multithreading_Signals_Posix - Fatal编程技术网

调用SIGINT时终止线程-C

调用SIGINT时终止线程-C,c,linux,multithreading,signals,posix,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_H

我正在构建一个用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()
!它不需要是异步信号安全的,请参阅

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

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
}

另外,用于安装信号处理程序。有关不使用它的原因,请参阅。

可能的信号副本已发送到主线程;只要退出()就可以了,操作系统会帮你清理的。我发誓,经过20分钟的深入搜索,我真的没有找到副本。Felix Palmen的答案比@Ctx的评论更受欢迎,因为在我的程序中,我使用的是套接字,如果在它们上打开了连接,那么即使没有人听,套接字也会在短时间内保持打开状态。无论如何,谢谢大家。谢谢你们提供的有用的链接和解释。我知道这与我的问题无关,但你能给我解释一下什么是sig_原子类型,为什么用它代替int?我知道在32位机器上整数是4字节,这更严格?它是一种保证用一条指令读写的类型。很有可能它只是一个
typedef
int
,但是可能有一些系统,
int
需要不止一条指令来读/写(例如,在8位体系结构上,
int
有16位),以便信号处理程序和主程序之间的值保持一致,只要始终使用volatile sig\u atomic\t。