如何使用信号从自身重新启动 BASH 脚本?
例如,我有一个无限循环的脚本,将某些内容打印到标准输出。我需要捕获一个信号(例如 SIGHUP),以便它将使用不同的 PID 重新启动脚本,并且循环将从 0 重新启动。终止和启动不能按预期工作:
function traphup(){
kill $0
exec $0
}
trap traphup HUP
也许我应该在后台放置一些东西或使用 nohup ,但我不熟悉这个命令。
For example I have script with an infinite loop printing something to stdout. I need to trap a signal (for example SIGHUP) so it will restart the script with different PID and the loop will start itself again from 0. Killing and starting doesn't work as expected:
function traphup(){
kill $0
exec $0
}
trap traphup HUP
Maybe I should place something in background or use nohup, but I am not familiar with this command.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的函数中:
这将使用原始命令名称和参数(根据您的要求改变参数)和新进程 ID 在后台启动一个新进程。然后原始 shell 退出。如果您的守护进程使用 PID 文件来识别自己,请不要忘记整理 PID 文件 - 但无论如何重新启动都可能会这样做。
请注意,使用
nohup
是错误的方向;第一次启动守护进程时,它会响应 HUP 信号,但使用nohup
启动的守护进程会忽略该信号,不会再次重新启动 - 除非您明确覆盖“忽略”状态,即由于各种原因,这是一个坏主意。回答评论
我不太确定问题是什么。
当我运行以下脚本时,无论我将其作为
./xx.sh
还是启动,我都只能在
.ps
输出中看到该脚本的一份副本./xx.sh &输出包含以下行:
带有 '
' 的行是原始进程;第二组是报告其父进程(1155)的子进程(1649)。此输出可以轻松跟踪将 HUP 信号发送到哪个进程。 (初始的 echo 和 sleep 使命令行提示符不再妨碍输出。)我怀疑您所看到的内容取决于脚本的内容 - 在我的例子中,循环体很简单。但如果我有管道或其他东西,那么我可能会看到第二个同名的进程。但我认为这不会根据原始脚本是在前台还是后台运行而改变。
In your function:
This starts a new process in the background with the original command name and arguments (vary arguments to suit your requirements) with a new process ID. The original shell then exits. Don't forget to sort out the PID file if your daemon uses one to identify itself - but the restart may do that anyway.
Note that using
nohup
would be the wrong direction; the first time you launched the daemon, it would respond to the HUP signal, but the one launched withnohup
would ignore the signal, not restarting again - unless you explicitly overrode the 'ignore' status, which is a bad idea for various reasons.Answering comment
I'm not quite sure what the trouble is.
When I run the following script, I only see one copy of the script in
ps
output, regardless of whether I start it as./xx.sh
or as./xx.sh &
.The output contains lines such as:
The ones with '
<none>
' are the original process; the second set are the child process (1649) reporting its parent (1155). This output made it easy to track which process to send HUP signals to. (The initial echo and sleep gets the command line prompt out of the way of the output.)My suspicion is that what you are seeing depends on the content of your script - in my case, the body of the loop is simple. But if I had a pipeline or something in there, then I might see a second process with the same name. But I don't think that would change depending on whether the original script is run in foreground or background.