我使用 init-script 作为守护进程运行我的脚本(套接字):
#!/bin/bash
### BEGIN INIT INFO
# Provides: sock_serv
# Required-Start: $local_fs $syslog $remote_fs
# Required-Stop: $local_fs $syslog $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: sock_servservice
# Description: Run sock_serv service
### END INIT INFO
# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting sock_serv..."
if sudo -u root bash -c 'cd ~/mypath/ && python3 sock_serv.py &> /dev/null &' ; then
echo "OK"
else
echo "Error: can't start "
fi
;;
stop)
echo "Stopping sock_serv..."
if sudo -u root bash -c 'cd ~/mypath/ && python3 stop_sock_serv.py &>/dev/null &'; then
# sleep 2
echo "OK"
else
echo "Error: can't stop "
fi
;;
*)
echo "Usage: /etc/init.d/sock_serv {start|stop}"
exit 1
;;
esac
我在sock_serv
模块中使用循环Select
来接收来自不同客户端的消息。
我可以运行我的sock_serv
,但几个小时后sock_serv
监听任何端口(停止)
当我运行service sock_serv status
bevor 并在 sock_serv 停止后我得到:
sock_serv.service - LSB: sock_serv service
Loaded: loaded (/etc/init.d/sock_serv; generated)
Active: active (exited) since Sat 2019-10-12 16:06:56 CEST; 23h ago
Docs: man:systemd-sysv-generator(8)
Tasks: 0 (limit: 2301)
Memory: 0B
CGroup: /system.slice/sock_serv.service
Oct 12 18:08:10 sam sudo[1042]: pam_unix(sudo:session): session closed for user root
Oct 12 18:08:10 sam sudo[1045]: root : TTY=unknown ; PWD=/root/mypath; USER=root ; COMMAND=/root/mypath/otherScript.py
Oct 12 18:08:10 sam sudo[1045]: pam_unix(sudo:session): session opened for user root by (uid=0)
Oct 12 18:08:10 sam sudo[1045]: pam_unix(sudo:session): session closed for user root
我希望 sock_serv 仍然持续运行。谢谢