首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >捕获信号SIGINT仍然杀死程序

捕获信号SIGINT仍然杀死程序
EN

Stack Overflow用户
提问于 2013-11-05 21:41:33
回答 1查看 1.5K关注 0票数 1

我正在编写我自己的mini bash,我想禁用默认的SIGINT行为(只有“退出”应该终止bash),但是SIGINT可能会杀死正在运行的子程序(例如,运行“睡眠60 \睡眠30")。

为了捕获SIGINT,我使用了signal(SIGINT, catchSignal);函数。问题是,将^C发送到我的迷你that中仍然会杀死它=(

根据GNU: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(),但只适用于运行子程序。

示例执行

代码语言:javascript
复制
[22:33:31][user][~/edu/sysprog/lab4]$ ./minibash 
mbash% ^CCatched Sigint
Inside Sigint
No children

代码:

代码语言:javascript
复制
#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

代码语言:javascript
复制
int main(void)
{

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

    signal(SIGINT, catchSignal);

    .......
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-05 22:19:57

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19799582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档