1

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

为了捕捉 SIGINT 我正在使用signal(SIGINT, catchSignal);函数。问题是在我的 minibash 中发送 ^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() 将被执行,除此之外什么都没有。对?

如果是,那么为什么我的 minibash 会终止,这就是我的 catchSignal()。它确实有kill(),但仅限于奔跑的孩子。

样品执行

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

代码:

#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)");
    }
}

代码2

int main(void)
{

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

    signal(SIGINT, catchSignal);

    .......
4

1 回答 1

4

我建议siginterrupt(SIGINT, 0);在建立信号处理程序之后添加一个,并阅读有关中断系统原语与signal(3).

于 2013-11-05T22:19:57.690 回答