2017-12-19 8 views
0

私は信号について学び、それらと一緒に演奏する簡単なプログラムを書いています。SIGaction does does work

私はフォークを使って数値を入力しています。私はプロセスを作成します。親プロセスはシグナルを子プロセスに送信し、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を設定しました。 –