调用 SIGINT 时终止线程 - C [英] Terminate threads when SIGINT is called - C
问题描述
我正在构建一个用 C-UNIX 编写的通用程序(使用 Linux,所以我不关心 BSD 或 WIN 函数),它创建了两个线程来处理与服务器的通信.
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.
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 的可能性,所以我用这行代码:
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:
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 是否正确还是应该使用其他方法?
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?
推荐答案
不要从信号处理程序中调用 pthread_exit()
!不需要async-signal-safe,参见信号安全.
Don't call pthread_exit()
from a signal handler! It is not required to be async-signal-safe, see 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 e.g.
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()
了解不使用它的原因.
Also, use sigaction()
for installing signal handlers. See signal()
for reasons not to use it.
这篇关于调用 SIGINT 时终止线程 - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!