如何向 bash 守护进程发送自定义信号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29321171/
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
How to send custom signal to bash daemon process?
提问by greenV
I have simple bash daemon running (with root privileges ) in background which suppose to do action1
or/and action2
when notified.
我有一个简单的 bash 守护进程在后台运行(具有 root 权限),假设会action1
或/和action2
在通知时运行。
How do I notify it/send some kind of signal on which it will react?
我如何通知它/发送某种信号,它会做出反应?
I've tried scenarios with checking file change every 1 sec or more often, but that's kind of less-desirable solution.
我已经尝试过每 1 秒或更频繁地检查文件更改的场景,但这是一种不太理想的解决方案。
采纳答案by kasperd
You can send signals to a process using the kill
command. There is a range of standard signals as well as two user defined signals, which you can let your script handle whichever way you prefer. Here is how this could look in a script
您可以使用该kill
命令向进程发送信号。有一系列标准信号以及两个用户定义的信号,您可以让脚本以您喜欢的任何方式处理它们。这是在脚本中的样子
#!/bin/bash
handler(){
echo "Handler was called"
}
trap handler USR1
while sleep 1
do
date
done
To send a signal to the script you first need to find the pid of the script and then use the kill
command. It could look like this kill -USR1 24962
.
要向脚本发送信号,您首先需要找到脚本的 pid,然后使用该kill
命令。它看起来像这样kill -USR1 24962
。
回答by kasperd
You can use the killcommand to send a process a signal. In bash, you can use the trapcommand to create a signal handler.
您可以使用kill命令向进程发送信号。在 bash 中,您可以使用trap命令来创建信号处理程序。
#!/bin/bash
# traptest.sh
trap "echo Booh!" SIGINT SIGTERM
echo "pid is $$"
while : # This is the same as "while true".
do
sleep 60 # This script is not really doing anything.
done