说明 当我们需要让Linux程序后台运行时,可以使用以下四种方式:添加&符号、nohup、screen以及systemctl。其中systemctl还可以配置开机自启动。
& 1 2 3 ./test & ps -ef|grep test killall test
nohup 1 2 3 4 5 which nohup apt install coreutils nohup ./test & nohup ./test > /dev/null 2>&1 & kill -9 PID
screen 1 2 3 4 5 6 apt install screen screen -S test Ctrl a+d screen -ls screen -x test screen -X -S test quit
systemctl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 nano /lib/systemd/system/test.service [Unit] Description=Test Service After=network.target [Service] ExecStart=/path/to/test.sh Restart=on-failure [Install] WantedBy=multi-user.target systemctl daemon-reload systemctl enable test systemctl disable test systemctl start test systemctl stop test systemctl restart test systemctl status test
alpine alpine没有systemd管理服务,因此需要安装openrc。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 apk add openrc nano /etc/init.d/test command ="/path/to/test" command_args="命令参数" command_background="yes" pidfile="/run/test.pid" depend () { need net } chmod +x /etc/init.d/test rc-service test start rc-service test stop rc-service test restart rc-service test status rc-update add test rc-update del test rc-update show