Bash 신호 트랩 상속

Bash 신호 트랩 상속

trap이 명령이 어떻게 작동하는지에 대한 명확하고 모호하지 않은 정보를 찾기 위해 고심하고 있습니다 .

특히, trap대본에 로컬 효과가 나타나는지? 나는 항상 그것이 사실이라고 생각했지만 반대 주장을 본 적이 있습니다. trap현재 스크립트에서 호출된 다른 쉘 스크립트에 영향을 줍 니까 ? 바이너리에 영향을 미치나요?

답변1

충분히 빠르게 테스트할 수 있습니다.

$ cat test.sh
trap : INT HUP USR1
sleep 10h
$ ./test.sh &
[1] 29668
$ grep SigCgt /proc/$(pgrep test.sh)/status
SigCgt: 0000000000010203
$ grep SigCgt /proc/$(pgrep sleep)/status
SigCgt: 0000000000000000

따라서 trap바이너리 파일은 영향을 받지 않습니다.

스크립트는 어떻습니까?

$ cat blah.sh 
#! /bin/bash    
grep SigCgt /proc/$$/status
$ cat test.sh 
#! /bin/bash
trap : INT HUP USR1
./blah.sh
$ ./test.sh 
SigCgt: 0000000000010002

그래서 뭔가가 잡혔습니다. 하지만 기다려!

$ ./blah.sh 
SigCgt: 0000000000010002

어쨌든 이 신호는 처리될 것 같습니다.


이것맨페이지그것은 말한다:

   When a simple command other than a builtin or shell function is  to  be
   executed,  it  is  invoked  in  a  separate  execution environment that
   consists of the following.  Unless  otherwise  noted,  the  values  are
   inherited from the shell.
   ...
   ·      traps caught by the shell are reset to the values inherited from
          the shell's parent, and traps ignored by the shell are ignored

해당 비트마스크를 신호 세트로 변환하려면 다음을 시도하십시오.

HANDLED_SIGS=$(awk '/SigCgt/{print "0x"$2}' /proc/$PID/status)
for i in {0..31} 
do 
    (( (1 << i) & $HANDLED_SIGS )) && echo $((++i)) $(/bin/kill --list=$i); 
done | column

이 경우 처리할 필요가 없는 신호 집합은 다음 trap과 같습니다.

$ HANDLED_SIGS=0x0000000000010002
$ for i in {0..31}; do (( (1 << i) & $HANDLED_SIGS )) && echo $((++i)) $(/bin/kill --list=$i); done | column
2 INT   17 CHLD

답변2

이게 답은 아니지만...

$ cat Trap.sh
#!/bin/bash

echo "Trap.sh is PID $$"
trap -p
grep Sig /proc/$$/status

trap 'echo SIGINT' SIGINT
trap -p
grep Sig /proc/$$/status

trap 'echo SIGTERM' SIGTERM
trap -p
grep Sig /proc/$$/status

trap 'echo SIGUSR1' SIGUSR1
trap -p
grep Sig /proc/$$/status

$ ./Trap.sh
Trap.sh is PID 13887
SigQ:   0/63517
SigPnd: 0000000000000000
SigBlk: 0000000000010000
SigIgn: 0000000000000004
SigCgt: 0000000043817efb
trap -- 'echo SIGINT' SIGINT
SigQ:   0/63517
SigPnd: 0000000000000000
SigBlk: 0000000000010000
SigIgn: 0000000000000004
SigCgt: 0000000043817efb
trap -- 'echo SIGINT' SIGINT
trap -- 'echo SIGTERM' SIGTERM
SigQ:   0/63517
SigPnd: 0000000000000000
SigBlk: 0000000000010000
SigIgn: 0000000000000004
SigCgt: 0000000043817efb
trap -- 'echo SIGINT' SIGINT
trap -- 'echo SIGUSR1' SIGUSR1
trap -- 'echo SIGTERM' SIGTERM
SigQ:   0/63517
SigPnd: 0000000000000000
SigBlk: 0000000000010000
SigIgn: 0000000000000004
SigCgt: 0000000043817efb

이것이 무엇을 의미하는지 이해하지 못합니다. 내 거추측하다모든 것을 포착한 다음 트랩 루틴 내에서 무엇을 할지 결정하는 것은 Bash입니다.

관련 정보