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

后端 未结 2 924
我寻月下人不归
我寻月下人不归 2021-01-24 19:45

I have the following code:

#include 
#include 
#include 

pthread_t test_thread;

void *thread_test_run (void *v)         


        
2条回答
  •  生来不讨喜
    2021-01-24 20:09

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

提交回复
热议问题