2016-10-25 4 views
-2

내가 온라인 튜토리얼에서 참조 신호 처리 프로그램 다음 시도했지만, 그것이 작동 보인다되지 않습니다, 내 코드에 어떤 문제가 있는지 :내 신호 처리기가 sigaction 기능을 사용하여 작동하지 않는 이유는 무엇입니까?

#include<signal.h> 
#include<unistd.h> 
#include<string.h> 
#include<stdio.h> 
#include<stdlib.h> 

typedef void (*SignalHandlerPointer)(int); 

static void UsrHostSigAbort(int pSignal) 
{ 
     //stopService(); 
    printf("pankaj"); 
} 
void HandleHostSignal() 
{ 
     struct sigaction satmp; 
     memset(&satmp, '\0' , sizeof(satmp)); 
     SignalHandlerPointer usrSigHandler; 
     satmp.sa_flags &= ~SA_SIGINFO; 
     satmp.sa_handler = UsrHostSigAbort; 
     usrSigHandler = sigaction (SIGINT , &satmp, NULL); 
} 

void main() 
{ 
HandleHostSignal(); 

while(1) 
{ 
sleep(1); 
} 
} 

내가 컴파일하고 우분투에서이 프로그램을 실행하고 있습니다.

+0

사용중인 운영 체제는 무엇입니까? – Ari0nhh

+0

@ Ari0nhh 우분투입니다.이 정보로 Q를 업데이트했습니다. –

+1

[신호 처리기에서'printf()'사용을 피하는 방법?] (http://stackoverflow.com/questions/16891019/) 아마 문제의 원인은 아니지만, 설명 된 문제를 알고 있어야합니다. –

답변

3

이 코드 - 기본적으로 코드 만 사소한 변형입니다 - 맥 OS 시에라 10.12.1에 제대로 실행 :

#include <signal.h> 
#include <stdio.h> 
#include <unistd.h> 

static void UsrHostSigAbort(int pSignal) 
{ 
    // stopService(); 
    // Using printf is not good - see: http://stackoverflow.com/questions/16891019/ 
    // It will suffice for this code, however. 
    printf("pankaj %d\n", pSignal); 
} 

static void HandleHostSignal(void) 
{ 
    struct sigaction satmp; 
    sigemptyset(&satmp.sa_mask); 
    satmp.sa_flags = 0; 
    satmp.sa_handler = UsrHostSigAbort; 
    sigaction(SIGINT, &satmp, NULL); 
} 

int main(void) 
{ 
    HandleHostSignal(); 

    while (1) 
    { 
     sleep(1); 
     putchar('.'); 
     fflush(stdout); 
    } 
} 

예 출력 (프로그램 sig19라고도 함) :

$ ./sig19 
......^Cpankaj 2 
.....^Cpankaj 2 
....^Cpankaj 2 
...^Cpankaj 2 
..^Cpankaj 2 
.^Cpankaj 2 
..................^\Quit: 3 
$ 

I을 종료 키 (내 터미널의 ^\)를 사용하여 프로그램을 중지하십시오.

+0

고마워요 조나단, 그 작업 –