如何在从“killall”或“kill -p pid”接收kill信号时退出程序之前执行处理函数?

我有以下代码:

#include  #include  #include  pthread_t test_thread; void *thread_test_run (void *v) { int i=1; while(1) { printf("into thread %d\r\n",i); i++; sleep(1); } return NULL } int main() { pthread_create(&test_thread, NULL, &thread_test_run, NULL); sleep (20); pthread_cancel(test_thread); sleep(100); // In this period (before the finish of myprogram), // I execute killall to kill myprogram // I want to add a signal handle function to // execute pthread_exit() before the program quit } 

我想通过添加一个信号句柄函数来完成我的代码,以便在程序退出之前执行pthread_exit()。

怎么做 ?

因为killall默认发送信号SIGTERM ,所以你可以处理这种类型的信号。

 #include  void handler(int sig) { /* ... */ } signal (SIGTERM, handler); 

这就是我在我的实用程序中实现某些你想要的东西的方法https://github.com/seriyps/wrk/commit/1d3c5dda0d46f0e567f3bae793bb3ae182de9438

 static thread *threads; int main(....){ ... sigint_action.sa_handler = &sig_handler; sigemptyset (&sigint_action.sa_mask); /* reset handler in case when pthread_cancel didn't stop threads for some reason */ sigint_action.sa_flags = SA_RESETHAND; sigaction(SIGTERM, &sigint_action, NULL); ... } static void sig_handler(int signum) { printf("interrupted\n"); for (uint64_t i = 0; i < cfg.threads; i++) { if(pthread_cancel(threads[i].thread)) exit(1); } }