2

我有以下代码:

#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() 来完成我的代码。

怎么做 ?

4

2 回答 2

4

因为默认killall发送信号SIGTERM,所以可以处理这种类型的信号。

#include <signal.h>

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

signal (SIGTERM, handler);
于 2012-11-09T14:04:33.550 回答
2

这就是我如何在我的实用程序中实现某种你想要的东西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);
    }
}
于 2012-11-09T15:56:49.120 回答