[英]Terminate threads when SIGINT is called - C
我正在构建一个用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");
}
由于此程序将从外壳启动,因此我想实现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()
的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.