bash - 如何从脚本向脚本发送信号 SIGINT?

标签 bash signals kill bash-trap

我想捕获从 Script-A.sh 发送到 Script-B.sh 的信号 所以在 Script-A.sh 中我使用命令:

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

然后在 Script-B.sh 中我捕获信号并调用函数 Clean

trap 'Clean' 2

它不起作用,相反,Script-B.sh 会在不执行清理的情况下立即被杀死!!

我还注意到,如果我想将 SIGINT 从终端发送到任何捕获它的脚本,ctrl-c 将被正确捕获,但如果我通过命令指定信号则不会kill -2 $pid_of_script

关于发送 SIGINT 的两种方法(ctrl-c VS kill -2 $pid_of_script)之间的区别的任何想法,以及我如何发送 SIGINT一个脚本到另一个?

最佳答案

我能够重现您报告的行为。我的假设是,由于脚本正在 非交互式 shell(作为脚本的子级)运行,因此 SIGINT 是一个键盘信号,被忽略。

来自 info bash:

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

我发现,如果您使用另一个信号(例如 SIGUSR1)trapkill,它会起作用。

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

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.

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

关于bash - 如何从脚本向脚本发送信号 SIGINT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2524937/

相关文章:

bash - 在同一行使用 grep 打印多个正则表达式匹配项

linux - Bash 等待多个同时的子进程并在出错时杀死所有子进程

javascript - 我怎样才能检测到我的 Node.js 脚本被永远终止了?

c++ - 程序可以在调用 kill 函数之前返回/终止吗?

c - 如何存储进程ID并杀死它们?

linux - 在具有完整路径的 Linux 中使用 ls 命令列出文件

bash - 使用 bash 如何在一行中获取网络设备名称和 IP 地址?

bash - 退出正在运行的脚本而不退出 shell

c - 如何强制将 SIGILL 发送到我的程序?

c - kill - 它会立即终止进程吗?