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

时间:2012-11-09 13:56:06

标签: c kill signal-handling

我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

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()。

怎么做?

2 个答案:

答案 0 :(得分:4)

由于killall默认发送信号SIGTERM,您可以处理此类信号。

#include <signal.h>

void handler(int sig)
{
     /* ... */
}

signal (SIGTERM, handler);

答案 1 :(得分:2)

这就是我在utilite 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);
    }
}