2017-12-19 21 views
0

나는 신호에 대해 배우고 있으며 그들과 함께하는 간단한 프로그램을 썼다.Sigaction doesnt work

그래서 숫자를 입력하고 fork를 사용하여 프로세스를 만듭니다. 부모 프로세스는 그 숫자를 자식 프로세스에 신호로 보내고, child_signal 핸들러는 신호로 제곱 된 숫자를 돌려 보내야합니다. .

이것은 코드입니다.

#include <iostream> 
#include <signal.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <sys/wait.h> 
#include <string.h> 
#include <errno.h> 
using namespace std; 

void child_handler(int sig_num){ 
    cout<<"Child recieved a signal"<<endl; 
    pid_t ppid = getppid(); 
    if(kill(ppid,sig_num*sig_num) == -1){ 
     cout<<"Childs signal handler failed to send a signal "<<endl; 

    } 
    cout<<"Sent a sgnal to the parent"<<endl; 
    return; 
} 

void parent_handler(int sig_num){ 
    cout<<"Parent recieved a signal "<<endl; 
    cout<<sig_num<<endl; 
    return; 
} 

int main(){ 
    int n; 
    cin>>n; 
    pid_t pid = fork(); 
    if(pid != 0){ 

     struct sigaction sa2; 
     memset(&sa2,0,sizeof(sa2)); 
     sa2.sa_handler = parent_handler; 

     if(sigaction(n,&sa2,NULL) == -1){ 
      cout<<"Parents sigaction failed "<<endl; 
     } 

     if(kill(pid,n) == -1){ 
      cout<<"Kill failed "<<endl; 
     } 
     cout<<"Sent a signal to the child"<<endl; 
     waitpid(pid,0,0); 
    } 
    else{ 

     struct sigaction sa1; 
     memset(&sa1,0,sizeof(sa1)); 
     sa1.sa_handler = child_handler;  

     if(sigaction(n,&sa1,NULL) == -1){ 
      cout<<"Childs sigaction failed eerno:"<<errno<<endl; 
     } 

     sleep(20); 

     return 0; 
    } 
    return 0; 
} 

출력은 다음과 같습니다.

아이에게 신호를 보냈습니다.

그리고 그것은 sigaction에 대해 아무 말도하지 않습니다.

+0

어떤 신호 번호를 보내고 있습니까? –

답변

0

코드에서 자식 프로세스는 처리기를 설정하기 전에 신호를받을 수 있습니다.

+0

어떻게 그럴 수 있습니까? 처음에는 sigaction을 설정했습니다. –