2014-10-09 25 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