2012-11-09 2 views
1

나는 다음과 같은 코드가 있습니다 :"killall"또는 "kill -p pid"에서 kill 신호를 수신 할 때 프로그램을 종료하기 전에 처리기 기능을 실행하는 방법은 무엇입니까?

나는 프로그램이 종료하기 전에가 pthread_exit()를 실행하기 위해 신호 핸들 기능을 추가하여 내 코드를 완료 할
#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 

} 

.

어떻게 만드시겠습니까?

+2

'참조 남자 signal'과'남자 sigaction' 내 utilite에서 원하는 어떤 종류의를 구현하는 방법이다. 당신이 어디서 어떻게 우리를 보여주는 실패하면 자신을 걷어차, 무언가를 시도하고 돌아와. – alk

답변

3

killall은 기본적으로 SIGTERM 신호를 보내므로이 유형의 신호를 처리 할 수 ​​있습니다.

#include <signal.h> 

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

signal (SIGTERM, handler); 
+0

어디에'signal (SIGTERM, handler);를 써 넣을까요? 'main()'의 시작 부분에? – MOHAMED

+0

예, 좋습니다. 핸들러를 설정하는 순간부터 작동해야합니다. – md5

+0

당신은 sigaction 대신에'signal'을 사용하지 말아야합니다. – iabdalkader

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

http : //리스트에없는 함수를 호출하는 중입니다. 핸들러의 man7.org/linux/man-pages/man7/signal.7.html은 안전하지 않습니다. – 2501