bash:为什么我不能在后台shell中设置SIGINT陷阱? [英] bash: Why can't I set a trap for SIGINT in a background shell?

查看:63
本文介绍了bash:为什么我不能在后台shell中设置SIGINT陷阱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的程序,它注册了两个 trap 处理程序,然后使用 trap -p 显示它们.然后,它执行相同的操作,但是在子级后台进程中.

Here's a simple program that registers two trap handlers and then displays them with trap -p. Then it does the same thing, but in a child background process.

为什么后台进程会忽略 SIGINT 陷阱?

Why does the background process ignore the SIGINT trap?

#!/bin/bash

echo "Traps on startup:"
trap -p
echo ""

trap 'echo "Received INT"' INT
trap 'echo "Received TERM"' TERM

echo "Traps set on parent:"
trap -p
echo ""

(
    echo "Child traps on startup:"
    trap -p
    echo ""

    trap 'echo "Child received INT"' INT
    trap 'echo "Child received TERM"' TERM

    echo "Traps set on child:"
    trap -p
    echo ""
) &

child_pid=$!
wait $child_pid

输出:

$ ./show-traps.sh
Traps on startup:

Traps set on parent:
trap -- 'echo "Received INT"' SIGINT
trap -- 'echo "Received TERM"' SIGTERM

Child traps on startup:

Traps set on child:
trap -- 'echo "Child received TERM"' SIGTERM

推荐答案

SIGINT SIGQUIT 在后台进程中被忽略(除非它们使用 set后台设置)-m ).这是一个(奇怪的)POSIX要求(请参见 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html 或我的SO问题

SIGINT and SIGQUIT are ignored in backgrounded processes (unless they're backgrounded with set -m on). It's a (weird) POSIX requirement (see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html or my SO question Why do shells ignore SIGINT and SIGQUIT in backgrounded processes? for more details).

此外,POSIX还要求:

Additionally, POSIX requires that:

输入子shell时,应忽略不被忽略的陷阱设置为默认操作,除非使用命令替换仅包含一个陷阱命令..

When a subshell is entered, traps that are not being ignored shall be set to the default actions, except in the case of a command substitution containing only a single trap command ..

但是,即使在重置后在子外壳中再次设置了INT处理程序,该外壳也将无法接收,因为它会被忽略(您可以尝试使用它,也可以使用 ps ).

However, even if you set the INT handler in the subshell again after it was reset, the susbshell won't be able to receive it because it's ignored (you can try it or you can inspect the signal ignore mask using ps, for example).

这篇关于bash:为什么我不能在后台shell中设置SIGINT陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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