无法在Ubuntu中捕获SIGPIPE信号

时间:2014-12-22 10:06:14

标签: c ubuntu-12.04 sigpipe

我遇到了一个SIGPIPE崩溃问题,我想记录它并尝试存在。
但我无法通过跟随代码捕获SIGPIPE。
我尝试使用“kill -s signal process”来验证我的代码,它适用于信号SIGINT,SIGSTOP,SIGSEGV和SIGALRM。
但在SIGPIPE上失败了。
如果我在这里遗漏任何东西,请你告诉我。

void handle_pipe(int sig)
{
    printf("SIG_PIPE happen, error code is %d", sig);
    exit(0);    
}   

int main(int argc, char **argv)
{
    struct sigaction action;
    sigemptyset(&action.sa_mask);
    action.sa_handler = handle_pipe;
    action.sa_flags = 0;
    //not work
    sigaction(SIGPIPE, &action, NULL);   //Not work with kill -13 process_id
    //works well
    sigaction(SIGINT, &action, NULL);    //work with kill -2 process_id
    sigaction(SIGSEGV, &action, NULL);   //work with kill -11 process_id
    sigaction(SIGALRM, &action, NULL);   //work with kill -14 process_id
    sigaction(SIGSTOP, &action, NULL);   //work with kill -17 process_id

    fooServer * pfooServer = new fooServer();
    while(1)
    {
        pfooServer->DoEvents();
    }
    delete pfooServer;
}

我的环境是Ubuntu 12.04 LTS

1 个答案:

答案 0 :(得分:1)

这个完整的代码示例适用于kill -13。我没有在这里测试ubuntu 12.04 LTS,但在RHEL 6.5上没问题。试试这个。如果它按预期工作,那么你的" fooServer"这正在改变SIGPIPE行为

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



void handle_pipe(int sig)
{
    printf("SIG_PIPE happen, error code is %d", sig);
    exit(0);    
}   

int main(int argc, char **argv)
{
    struct sigaction action;
    sigemptyset(&action.sa_mask);
    action.sa_handler = handle_pipe;
    action.sa_flags = 0;
    //not work
    sigaction(SIGPIPE, &action, NULL);   //Not work with kill -13 process_id
    //works well
    sigaction(SIGINT, &action, NULL);    //work with kill -2 process_id
    sigaction(SIGSEGV, &action, NULL);   //work with kill -11 process_id
    sigaction(SIGALRM, &action, NULL);   //work with kill -14 process_id
    sigaction(SIGSTOP, &action, NULL);   //work with kill -17 process_id

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