如何从“killall”或“杀-p PID”杀接收信号时,之前执行的处理函数退出程序?(How to

2019-08-02 13:14发布

我有以下代码:

#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()程序退出之前完成我的代码。

怎么做 ?

Answer 1:

由于killall发送信号SIGTERM在默认情况下,您可以处理这种类型的信号。

#include <signal.h>

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

signal (SIGTERM, handler);


Answer 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);
    }
}


文章来源: How to execute a handler function before quit the program when receiving kill signal from“killall” or “kill -p pid”?