我试图用信号(SIGUSR1)中断readline,但显然如果信号没有被处理,程序就会退出,在处理时,它会继续readline,就好像什么都没发生一样。readline 是否应该能够使用信号中断。
我从另一个问题中得到了这个想法:force exit from readline() function
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <readline/readline.h>
#include <pthread.h>
pthread_t main_id;
void *thread_main(void* arg)
{
sleep(10);
pthread_kill(main_id, SIGUSR1);
}
void signal_handler(int sig)
{
puts("got signal");
(void) sig;
}
int main(int argc, char** argv)
{
struct sigaction sa;
sa.sa_handler = signal_handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGUSR1, &sa, NULL);
main_id = pthread_self();
pthread_t id;
pthread_create(&id, NULL, thread_main, NULL);
char *input = readline("prompt> ");
puts("main thread done");
return 0;
}
输出:
$ ./test
prompt> got signal
enter something
main thread done
$
谢谢。