bash 用于生成进程的 shell 脚本,在 SIGTERM 上终止子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/976059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:57:19  来源:igfitidea点击:

shell script to spawn processes, terminate children on SIGTERM

bashscriptingshlong-running-processessigterm

提问by itsadok

I want to write a shell script that spawns several long-running processes in the background, then hangs around. Upon receiving SIGTERM, I want all the subprocesses to terminate as well.

我想编写一个 shell 脚本,在后台生成几个长时间运行的进程,然后挂起。收到 SIGTERM 后,我希望所有子进程也终止。

Basically, I want a "master process".

基本上,我想要一个“主进程”。

Here's what I got so far:

这是我到目前为止所得到的:

#!/bin/sh

sleep 600 &
PID1="$!"

sleep 600 &
PID2="$!"

# supposedly this should kill the child processes on SIGTERM. 
trap "kill $PID1 $PID2" SIGTERM 

wait

The above script fails with trap: 10: SIGTERM: bad trap.

上面的脚本失败了trap: 10: SIGTERM: bad trap

Edit: I'm using Ubuntu 9.04

编辑:我使用的是 Ubuntu 9.04

采纳答案by itsadok

Joe's answer put me on the right track. I also found out I should trap more signals to cover my bases.

乔的回答让我走上了正轨。我还发现我应该捕获更多信号来覆盖我的基地。

Final script looks like this:

最终脚本如下所示:

#!/bin/sh

sleep 600 &
PID1="$!"

sleep 600 &
PID2="$!"

trap "kill $PID1 $PID2" exit INT TERM

wait

回答by tokland

This works for me:

这对我有用:

trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
  • kill -- -$$sends a SIGTERMto the whole process group, thus killing also descendants.

  • Specifying signal EXITis useful when using set -e(more details here).

  • kill -- -$$向整个进程组发送一个SIGTERM,从而也杀死了后代。

  • EXIT使用时指定信号很有用set -e(更多详细信息在这里)。

回答by TheBonsai

I suspect your /bin/sh is not a Bash (though you tagged the question as 'Bash').

我怀疑您的 /bin/sh 不是 Bash(尽管您将问题标记为“Bash”)。

From the message I guess it's a DASH. Check its manual or just fix your shebang if you need to write Bash code.

从消息中我猜它是一个 DASH。如果您需要编写 Bash 代码,请查看其手册或仅修复您的 shebang。

回答by TheBonsai

This script looks correct and works for me as expected.

这个脚本看起来正确并且按预期对我有用。

How do you send the SIGTERM signal to the "master process"? Maybe you should execute kill -lto check which signals are supported. As the error message suggests you send signal "10" which your system doesn't seem to recognize.

你如何将 SIGTERM 信号发送到“主进程”?也许您应该执行kill -l以检查支持哪些信号。由于错误消息表明您发送了系统似乎无法识别的信号“10”。

And next time you should add operating system, shell version, kernel, ... for such a question

下次你应该添加操作系统,shell版本,内核,......对于这样的问题