如何从bash脚本执行的bash脚本返回PID
下面的get_pid()函数用于返回如何从bash脚本执行的bash脚本返回PID,bash,ubuntu-16.04,daemon,Bash,Ubuntu 16.04,Daemon,下面的get_pid()函数用于返回守护进程的pid。sh 下面的脚本与daemon\u-tinerary.sh不在同一工作目录中 #!/bin/bash PID="" get_pid() { PID='pidof daemon_itinerary.sh' } start() { echo "Restarting test_daemon" get_pid if [[ -z $PID ]]; then echo "starting test_d
守护进程的pid。sh
下面的脚本与daemon\u-tinerary.sh
不在同一工作目录中
#!/bin/bash
PID=""
get_pid() {
PID='pidof daemon_itinerary.sh'
}
start() {
echo "Restarting test_daemon"
get_pid
if [[ -z $PID ]]; then
echo "starting test_daemon .."
sh /var/www/bin/daemon_itinerary.sh &
get_pid
echo "done. PID=$PID"
else
echo "test_deamon is alrady running, PID=$PID"
fi
}
case "$1" in
start)
start
;;
...
*)
echo "Usage: $0 {start|stop|restart|status}"
esac
*编辑
Start作为命令行参数传入 我们使用pgrep获得如下流程的pid
PID=$(pgrep -f "daemon_itinerary.sh" | xargs)
# xargs - is given because pgrep will return both process id as well as parent pid
# also it will help us to get all pids if multiple instances are running.
# pgrep option to get session id or parent id alone, here its from manual
# -P, --parent ppid,...
# Only match processes whose parent process ID is listed.
# -s, --session sid,...
# Only match processes whose process session ID is listed. Session ID 0 is translated into pgrep's or pkill's own session ID.
那么,问题是什么-|您不是从任何地方调用start()吗?pidof daemon_Cinerary.sh应该是反勾,而不是单引号。使daemon_Cinerary.sh可执行(700)并直接调用,而不是使用“sh”。然后使用'pidof-x daemon_-itinery.sh'实际上不是,正如Roadawl建议的那样,您应该使用pidof-x daemon_-itinery.sh。要在变量中捕获PID,它应该是PID=$(pidof daemon_tinerary.sh)。请注意pid变量的小写字母,因为pid在bash中是保留名称。