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
870 views
in Technique[技术] by (71.8m points)

bash - How to send a signal SIGINT from script to script?

I want to trap a signal send from Script-A.sh to Script-B.sh so in Script-A.sh i use the command:

(Send SIGINT to Script-B.sh)
kill -2 $PID_Script-B.sh

And in Script-B.sh i catch the signal and call function Clean

trap 'Clean' 2

It does not work, instead the Script-B.sh is killed right away without performing the Clean !!

What i notice also is that if i want to send SIGINT from terminal to any script that traps it, a ctrl-c will be caught correctly, but not if i specify the signal via the command kill -2 $pid_of_script

Any idea about the difference between the two method to send the SIGINT (ctrl-c VS kill -2 $pid_of_script), and how i can send a SIGINT from a script to another?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I was able to reproduce the behavior you report. My hypothesis is that since the script is running from a non-interactive shell (as a child of a script) that SIGINT, which is a keyboard signal, is ignored.

From info bash:

Background processes are those whose process group ID differs from the terminal's; such processes are immune to keyboard-generated signals.

I have found that if you trap and kill using another signal such as SIGUSR1 it works.

Additional information from man bash:

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.

and

If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.

and

Any trap on SIGCHLD is executed for each child that exits.


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

...