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

核能气质少年 提交于 2020-01-11 12:35:21

问题


I have the following code:

#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

}

I want to complete my code by adding a signal handle function to execute pthread_exit() before the program quit.

How to do it ?


回答1:


Because killall sends the signal SIGTERM by default, you can handle this type of signal.

#include <signal.h>

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

signal (SIGTERM, handler);



回答2:


This is how I implement some sort of what you want in my 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);
    }
}


来源:https://stackoverflow.com/questions/13309415/how-to-execute-a-handler-function-before-quit-the-program-when-receiving-kill-si

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!