2014-10-09 55 views
0

我是LINUX C編程新手,我的任務是編寫一個關於進程的程序。如何在父進程中捕捉術語動作信號?

我需要處理兩個進程,父進程和子進程。

我的目標是讓父叉進程(子進程),然後子進程執行可能會終止的程序失敗。父進程等待子進程終止,並獲取從子信號發起的信號,如中止或分段錯誤。

但是,我遇到一些問題。

我發現「Core Action」信號可以很容易的被檢測到,但是「Term action」無法被檢測到!

無法檢測到「術語操作」信號,例如SIGALRM(14)或SIGINT(2)。 它似乎被歸類爲終止成功。

這裏是我的代碼:

#include <cstdio> 
#include <cstdlib> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <signal.h> 
#include <cstring> 
#include <errno.h> 
using namespace std; 


bool check = true; 

void mySignal(int sig){ 
    int status; 
    pid_t childPid = wait(&status) ; 


    if(WIFEXITED(status)){ 
     printf("The child is terminated success!!\n"); 
    } 
    else{ 
     if(WIFSIGNALED(status)){ 
      int termsig = WTERMSIG(status) ; 
      printf("termsig = %d %d\n",status, termsig) ; 
     } 
    } 
    check = false ; 
} 


int main(int argc , char *argv[]){ 

    signal(SIGCHLD, mySignal) ; 
    pid_t pid = fork() ; 


    if(pid < 0){ 
     printf("fork error\n"); 
     exit(-1) ; 
    } 
    else if(pid == 0){ 
     execl(argv[1], NULL); 
     exit(0) ; 
    } 

    while(check) ; 
    return 0 ; 
} 

有誰知道如何解決這個問題?

回答

0
void mySignal(int sig){ 
    int status; 
    pid_t childPid = wait(&status) ; 


    if(WIFEXITED(status)){ 
    printf("The child is terminated success!!\n"); 
    } 

    if(WIFSIGNALED(status)){ 
    int termsig = WTERMSIG(status) ; 
    printf("termsig = %d %d\n",status, termsig) ; 
    } 
    check = false ; 
} 

信號並不總是結束一個程序,使您的條件無意義。

+0

哦!感謝您的提醒!我會考慮這個問題:) – ChihMin 2014-10-10 08:33:57

+0

@ChihMin不要忘記驗證一個答案,如果有人解決了你的問題。 – Mekap 2015-04-28 08:46:33

0

你應該做這樣的事情:

if(WEXITED(status)){ 
    printf("Child %d exited with exit code %d.\n", (int)pid, WEXITSTATUS(status)); 
    // Note that a non-zero exit status normally indicates some kind of error. 
} 
else if(WIFSIGNALED(status)){ 
    printf(
    "Child %d terminated with signal %d, with%s a core dump.\n", 
    (int)pid, WTERMSIG(status), WCOREDUMP(status)? "": "out" 
); 
} 
else if(WSTOPPED(status)){ 
    printf("Child %d was stopped by signal %d.\n", (int)pid, WSTOPSIG(status)); 
} 
else{ 
    fprintf(stderr, "Unexpected signal condition.\n"); 
} 

如上所述,一個非零退出狀態通常表示錯誤。所以你應該在你的代碼中執行:在execl()之後的exit(0)僅在對execl()的調用失敗時纔會執行,因此你寧願說一些類似exit(1)exit(EX_UNAVAILABLE)(來自<sysexits.h>)。

+0

哦!!!!!!所以這就是它! 感謝您的回答:) – ChihMin 2014-10-10 04:45:45

+0

但最後,我發現我的報警測試程序有些問題,導致我的父進程無法接收到SIGALRM信號XD – ChihMin 2014-10-10 05:19:20