问题
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