捕获信号SIGINT仍会导致程序死亡

时间:2013-11-05 21:41:34

标签: c linux signals

我正在编写自己的迷你bash并且我想禁用默认的SIGINT行为(只有“exit”应该终止bash)但是SIGINT可能会杀死正在运行的子行为(例如运行“sleep 60 | sleep 30”)。

为了捕获SIGINT我正在使用signal(SIGINT, catchSignal);函数。问题是在我的迷你垃圾箱内发送^ C仍然会杀死它=(

根据GNU:http://www.gnu.org/software/libc/manual/html_node/Basic-Signal-Handling.html

编辑:也许值得一提的是它在Mac上运行,而不是在Linux上运行!

A signal handler is just a function that you compile together with the rest of the program. Instead of directly invoking the function, you use signal or sigaction to tell the operating system to call it when a signal arrives.

所以我明白,当我按下^ C时,我的catchSignal()将被执行而不是这样。正确?

如果是,那么为什么我的miniash终止,这是我的catchSignal()。它确实有kill()但仅适用于跑步儿童。

示例执行

[22:33:31][user][~/edu/sysprog/lab4]$ ./minibash 
mbash% ^CCatched Sigint
Inside Sigint
No children

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <signal.h>

#include "sighant.h"

// Global variable
extern pidList children;

void catchSignal(int recvSign)
{
    printf("Catched Sigint\n");
    if(recvSign == SIGINT)
    {
        printf("Inside Sigint\n");
        if(children.count < 1)
        {
            printf("No children\n");
        }

        for(int i = 0; i < children.count; i++)
        {
            if(children.child[i] >= 0)
            {
                printf("KILLIN\n\n");
                kill(children.child[i], SIGKILL);
            }
        }
    }
    else
    {
        fprintf(stderr, "[ERROR] Could not execute Signal! (reason uknown)");
    }
}

CODE2

int main(void)
{

    fprintf(stderr, "mbash%% ");
    fflush(stderr);

    signal(SIGINT, catchSignal);

    .......

1 个答案:

答案 0 :(得分:4)

我建议在建立信号处理程序后添加siginterrupt(SIGINT, 0);,并阅读有关被中断的系统原语与signal(3)的对比。