Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

signals - bash: Why can't I set a trap for SIGINT in a background shell?

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.

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

Output:

$ ./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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

Additionally, POSIX requires that:

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 ..

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...