Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

如何让Linux程序后台运行

By: wayen
29 July 2023 at 05:18

如何让Linux程序后台运行

发表于|更新于|实用教程
|字数总计:416|阅读时长:1分钟|阅读量:

说明

当我们需要让Linux程序后台运行时,可以使用以下四种方式:添加&符号、nohup、screen以及systemctl。其中systemctl还可以配置开机自启动。

&

1
2
3
./test &    #在可执行程序后空一格添加&
ps -ef|grep test #查看是否在后台运行,可查看PID
killall test #关闭后台运行或kill -9 PID

nohup

1
2
3
4
5
which nohup    #查询是否安装nohup,输出/usr/bin/nohup则已安装
apt install coreutils #安装nohup
nohup ./test & #会输出nohup.out文件
nohup ./test > /dev/null 2>&1 & #关闭输出
kill -9 PID #关闭后台运行

screen

1
2
3
4
5
6
apt install screen    #安装screen
screen -S test #创建一个名为test的窗口并进入
Ctrl a+d #退出窗口但不关闭,使用exit退出且关闭窗口
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 #输入以下内容
#!/sbin/openrc-run

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 #查看所有开机自启
文章作者: wayen
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Wayen

评论
数据库加载中

❌
❌