从脚本 foo 终止 shell 脚本栏
Terminating a shell script bar from a script foo
我有一个脚本 foo
,如果提供一个参数 start
,它会在后台启动一个脚本 bar
并退出 - bar
包含一个无限循环。
在稍后的阶段,我想用参数 stop
调用 foo
,我希望仍然在后台运行的脚本 bar
停止 运行 .
课本上的实现方式是什么?
如果多个 bar
实例可以同时 运行,并且 foo stop
应该全部 stop/kill,请使用 pkill
:
$ pkill bar
杀死所有名为 bar
.
的进程
如果只允许一个 bar
实例 运行,则 "pidfile" 的解决方案是可行的。
在foo
中:
pidfile=/var/run/bar.pid
if ((start)); then
if [ -e "$pidfile" ]; then
echo "$pidfile exists."
# clean-up, or simply abort...
exit 1
fi
bar &
echo $! >"$pidfile"
fi
if ((stop)); then
if [ ! -e "$pidfile" ]; then
echo "$pidfile not found."
exit 1
fi
kill "$(<"$pidfile")"
rm -f "$pidfile"
fi
There are better ways to do what you're trying to do I believe 如果您的主机有 systemd 或 initd,则已经有框架可以拥有具有 start/stop 能力的长期 运行 作业。
如果你必须独立于那些或其他有用的工具来做这件事,我会这样解决它:
当您调用 foo start
时,将新生成的 bar
进程的 PID 存储在一个文件中,让我们称之为 pidfile
。这也可以是换行符分隔的 PID 列表。
当您调用 foo stop
时,使用 pkill -F pidfile
杀死所有 PID 与 pidfile
匹配的 运行 个进程
或者,当您调用 foo stop
时,您可以使用 pkill
来发现所有符合特定条件的进程的 PID。这可能更容易,但也可能更脆弱。
我有一个脚本 foo
,如果提供一个参数 start
,它会在后台启动一个脚本 bar
并退出 - bar
包含一个无限循环。
在稍后的阶段,我想用参数 stop
调用 foo
,我希望仍然在后台运行的脚本 bar
停止 运行 .
课本上的实现方式是什么?
如果多个 bar
实例可以同时 运行,并且 foo stop
应该全部 stop/kill,请使用 pkill
:
$ pkill bar
杀死所有名为 bar
.
如果只允许一个 bar
实例 运行,则 "pidfile" 的解决方案是可行的。
在foo
中:
pidfile=/var/run/bar.pid
if ((start)); then
if [ -e "$pidfile" ]; then
echo "$pidfile exists."
# clean-up, or simply abort...
exit 1
fi
bar &
echo $! >"$pidfile"
fi
if ((stop)); then
if [ ! -e "$pidfile" ]; then
echo "$pidfile not found."
exit 1
fi
kill "$(<"$pidfile")"
rm -f "$pidfile"
fi
There are better ways to do what you're trying to do I believe 如果您的主机有 systemd 或 initd,则已经有框架可以拥有具有 start/stop 能力的长期 运行 作业。
如果你必须独立于那些或其他有用的工具来做这件事,我会这样解决它:
当您调用 foo start
时,将新生成的 bar
进程的 PID 存储在一个文件中,让我们称之为 pidfile
。这也可以是换行符分隔的 PID 列表。
当您调用 foo stop
时,使用 pkill -F pidfile
杀死所有 PID 与 pidfile
或者,当您调用 foo stop
时,您可以使用 pkill
来发现所有符合特定条件的进程的 PID。这可能更容易,但也可能更脆弱。