无法在后台shell中捕获SIGINT信号 [英] Unable to trap SIGINT signal in a background shell

查看:95
本文介绍了无法在后台shell中捕获SIGINT信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在子进程/后台进程中运行时,我无法捕获信号.

I am unable to trap a signal when running in a child / background process.

这是我简单的bash脚本:

Here is my simple bash script:

#!/bin/bash

echo "in child"

trap "got_signal" SIGINT

function got_signal {
  echo "trapped"
  exit 0
}

while [ true ]; do
    sleep 2
done

在运行此功能并稍后运行时

When running this and later do

kill -SIGINT (pid)

一切正常,将打印被困并退出.

everything works as expected, it prints trapped and exits.

现在,如果我从这样的父脚本中启动相同的脚本:

Now, if I start the same script from a parent script like this:

#!/bin/bash

echo "starting the child"

./child.sh &

然后孩子不再捕获信号了....?

Then the child does not trap the signal anymore.... ?

更改为使用SIGTERM而不是SIGINT后,它似乎可以正常工作...?

After changing to use SIGTERM instead of SIGINT, it seems to be working correctly... ?

推荐答案

OSX上的 bash 联机帮助页(但在其他版本中应该相同)中对信号处理的说法如下:

The bash manpage on OSX (but it should be the same in other versions) has this to say about signal handling:

bash 运行的非内置命令将信号处理程序设置为以下值由外壳程序从其父级继承.当作业控制不在时效果是,异步命令除了会忽略 SIGINT SIGQUIT 这些继承的处理程序.

Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers.

,然后在 trap 命令下:

进入外壳时忽略的信号不能被困或重置.

Signals ignored upon entry to the shell cannot be trapped or reset.

由于默认情况下脚本不使用作业控制,所以这就是您要讨论的情况.

Since scripts don't use job control by default, this means the case you're talking about.

这篇关于无法在后台shell中捕获SIGINT信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆