我想更新,nc_pid
这样我就可以用它来检查带有 pid 的进程是否nc_pid
正在运行。
#!/usr/bin/bash
function start () {
trap 'echo "Clean up and exit"; kill $nc_pid; exit' TERM
exec > outfile
exec 2> errfile
exec 0< /dev/null
while true; do
(nc -lkp 1234 -e /usr/bin/bash &>/dev/null) &
nc_pid=$! # global variable nc_pid is not updated
wait $nc_pid
kill $nc_pid &>/dev/null
done
}
if [ "$1" != "__forked__" ]; then
setsid "$0" __forked__ "$@" &
exit
else
shift
fi
# stop or start daemon
nc_pid=999999
case "$1" in
stop)
killall simpled.sh
;;
start)
if ! kill -0 $nc_pid &>/dev/null # always false
then
start
fi
;;
status)
if kill -0 $nc_pid &>/dev/null # always false
then
echo "nc running"
else
echo "nc not running"
fi
;;
*)
echo -e "\nsimpled.sh [start|stop|status]"
;;
esac
最初nc_pid
设置为通常不存在的值 (999999)。然后我想在运行时nc_pid
更新分叉nc
进程的 pid。start()
但似乎nc_pid
根本没有更新(值保持为 999999)。
因此$0 start
总是启动分叉进程的新实例nc
并$0 status
始终输出“nc not running”。
如何修复代码,以便从外部nc_pid
获取分叉进程的 pid ?谢谢!nc
start()
答案1
我只是将 nc 的 pid 保存到文件中并以这种方式修复它。
#!/usr/bin/bash
function start () {
trap 'echo "Clean up and exit"; kill $nc_pid; rm nc_pid; exit' TERM
exec > outfile
exec 2> errfile
exec 0< /dev/null
while true; do
(nc -lkp 1234 -e /usr/bin/bash &>/dev/null) &
nc_pid=$!
echo $nc_pid > nc_pid
wait $nc_pid
kill $nc_pid &>/dev/null
done
}
if [ "$1" != "__forked__" ]; then
setsid "$0" __forked__ "$@" &
exit
else
shift
fi
# stop or start daemon
([ ! -f "nc_pid" ] && nc_pid=9999) || nc_pid=$(cat nc_pid)
case "$1" in
stop)
killall simpled.sh
;;
start)
if ! kill -0 $nc_pid &>/dev/null
then
start
fi
;;
status)
if kill -0 $nc_pid &>/dev/null
then
echo -e "\nnc running: pid $nc_pid"
else
echo -e "\nnc not running"
fi
;;
*)
# when $0 is run, the help message displays then won't return to terminal until return key is pressed.
echo -e "\nsimpled.sh [start|stop|status]"
;;
esac
干杯!