gpt4 book ai didi

c - 信号捕获和线程终止的问题 - C

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:46 24 4
gpt4 key购买 nike

我正在用 c 编写一个程序,它使用线程,我还想从用户那里捕获 Ctrl+C 信号。因此,在我使用多线程之前,我会捕获信号。

我的主线程(我的意思是除了程序运行的实际主线程之外)是一种处理用户输入的方法,我还将这个线程加入到主程序线程中。

问题是,当测试并按 Ctrl+C 退出程序时,负责接收用户输入的线程直到我在键盘上点击“返回”才会关闭——就像它卡在无限循环中一样。

当通过键入“q”退出时,所有线程都会正常结束。

我使用一个全局变量 exit_flag 来指示线程完成它们的循环。

此外,在 init_radio_stations 方法中有另一个单线程创建,它以完全相同的方式循环 - 在 exit_flag 状态下,并且这个线程正确关闭

这是我的主循环代码:

void main_loop()
{
status_type_t rs = SUCCESS;
pthread_t thr_id;

/* Catch Ctrl+C signals */
if(SIG_ERR == signal(SIGINT, close_server)) {
error("signal() failed! errno = ");
}

printf("\n~ Welcome to radio_server! ~\n Setting up %d radio stations... ", srv_params.num_of_stations);
init_radio_stations();
printf("Done!\n\n* Hit 'q' to exit the application\n* Hit 'p' to print stations & connected clients info\n");

/* Create and join a thread to handle user input */
if(pthread_create(&thr_id, NULL, &rcv_usr_input, NULL)) {
error("main_loop pthread_create() failed! errno = ");
}
if(pthread_join(thr_id, NULL)) {
error("main_loop pthread_join() failed! errno = ");
}
}

关闭服务器方法:

void close_server(int arg)
{
switch(arg) {
case SIGINT: /* 2 */
printf("\n^C Detected!\n");
break;

case ERR: /* -1 */
printf("\nError occured!\n");
break;

case DEF_TO: /* 0 */
printf("\nOperation timed-out!\n");
break;

default: /* will handle USER_EXIT, and all other scenarios */
printf("\nUser abort!\n");
}

printf("Signaling all threads to free up all resources and exit...\n");

/* Update exit_flag, and wait 1 sec just in case, to give all threads time to close */
exit_flag = TRUE;
sleep(1);
}

和rcv_usr_input句柄代码:

void * rcv_usr_input(void * arg_p)
{
char in_buf[BUFF_SIZE] = {0};

while(FALSE == exit_flag) {
memset(in_buf, 0, BUFF_SIZE);

if(NULL == fgets(in_buf, BUFF_SIZE, stdin)) {
error("fgets() failed! errno = ");
}

/* No input from the user was received */
if('\0' == in_buf[0]) {
continue;
}

in_buf[0] = tolower(in_buf[0]);
if( ('q' == in_buf[0]) && ('\n' == in_buf[1]) ) {
close_server(USER_EXIT);
} else {
printf("Invalid input!\nType 'q' or 'Q' to exit only\n");
}
}

printf("User Input handler is done\n");
return NULL;
}

我猜我的问题与在主循环结束时加入使用 rcv_usr_input 的线程有关,但我无法弄清楚到底是什么导致了这种行为。

我很乐意得到一些帮助,谢谢

最佳答案

Mike 和 Kaylum 已经正确地识别了 fgets() 阻塞的根本问题。然而,更大的问题仍然存在:当进程收到 SIGINT 时如何终止阻塞线程。有几种解决方案。

Thead 分遣队:一种解决方案是分离阻塞线程,因为分离线程不会阻止进程在最后一个非分离线程终止时终止。通过在其上调用 pthread_detach() 来分离线程,例如,

#include <pthread.h>
// Called by pthread_create()
static void* start(void* arg)
{
pthread_detach();
...
}

或者通过使用 PTHREAD_CREATE_DETACHED 属性创建线程,例如,

#include <pthread.h>
...
pthread_attr_t attr;
(void)pthread_attr_init(&attr);
(void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
...
(void)pthread_t thread;
(void)pthread_create(&thread, &attr, ...);

请注意,pthread_join() 不应在分离的线程上调用。

信号转发:另一种解决方案是不分离阻塞线程,而是通过pthread_kill()SIGINT等信号转发给线程,如果阻塞线程没有收到信号,例如,

#include <pthread.h>
#include <signal.h>
...
static pthread_t thread;
...
static void handle_sigint(int sig)
{
if (!pthread_equal(thread, pthread_self()) // Necessary
(void)pthread_kill(thread, SIGINT);
}
...
sigaction_t sigaction;
sigaction.sa_mask = 0;
sigaction.sa_flags = 0;
sigaction.sa_handler = handle_sigint;
(void)sigaction(SIGHUP, &sigaction, ...);
...
(void)pthread_create(&thread, ...);
...
(void)pthread_join(thread, ...);
...

这将导致阻塞函数返回,并将 errno 设置为 EINTR

请注意,未指定在多线程进程中使用 signal()

线程取消:另一种解决方案是通过pthread_cancel()取消阻塞线程,例如

#include <pthread.h>
...
static void cleanup(...)
{
// Release allocated resources
...
}
...
static void* start(void* arg)
{
pthread_cleanup_push(cleanup, ...);
for (;;) {
...
// Call the blocking function
...
}
pthread_cleanup_pop(...);
...
}
....
static void handle_sigint(int sig)
{
(void)pthread_cancel(thread);
}
...
sigaction_t sigaction;
sigaction.sa_mask = 0;
sigaction.sa_flags = 0;
sigaction.sa_handler = handle_sigint;
(void)sigaction(SIGHUP, &sigaction, ...);
...
(void)pthread_create(&thread, ..., start, ...);
...
(void)pthread_join(thread, ...);
...

对于在调用 select()poll() 时阻塞的线程,还有另一种解决方案:创建一个文件描述符,阻塞函数也在该文件描述符上等待,并且在收到适当的信号后关闭该描述符——但可以说,该解决方案超出了该问题的范围。

关于c - 信号捕获和线程终止的问题 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com