当我的 shell 脚本退出时,如何终止后台进程/作业? [英] How do I kill background processes / jobs when my shell script exits?

查看:64
本文介绍了当我的 shell 脚本退出时,如何终止后台进程/作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的顶级脚本退出时,我正在寻找一种清理混乱的方法.

I am looking for a way to clean up the mess when my top-level script exits.

特别是如果我想使用set -e,我希望脚本退出时后台进程会死.

Especially if I want to use set -e, I wish the background process would die when the script exits.

推荐答案

为了清理一些乱七八糟的东西,可以使用trap.它可以提供特定信号到达时执行的内容列表:

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

但也可用于在 shell 退出时执行某些操作:

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

它是一个内置函数,所以 help trap 会给你信息(与 bash 一起使用).如果你只想杀死后台工作,你可以这样做

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

注意使用单个 ',以防止 shell 立即替换 $().

Watch out to use single ', to prevent the shell from substituting the $() immediately.

这篇关于当我的 shell 脚本退出时,如何终止后台进程/作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆