本文介绍如何通过systemd配置文件,在网络启动后自动启动/home/ubuntu/Desktop/test文件夹下的程序,并提供详细指导步骤
编写配置文件
1.查看第一个进程是否为systemd,命令为:
ps -e
2.打开终端,使用以下命令创建一个名为restart.service(名字可以按自己想法来命名)的服务配置文件:
sudo vim /etc/systemd/system/restart.service
3.将以下内容写入到配置文件中:
[Unit]
Description=Demo Service
After=network.target
[Service]
WorkingDirectory=/home/ubuntu/Desktop/test
ExecStart=/home/ubuntu/Desktop/test/demo &!
Restart=always
[Install]
WantedBy=multi-user.target
4.保存并退出配置文件。
配置文件生效
1.重新加载systemd配置:
sudo systemctl daemon-reload
2.启动restart服务:
sudo systemctl start restart
3.验证服务是否启动:
sudo systemctl status restart
如果服务已经成功启动,可以看到以下内容的输出:
● restart.service - Demo Service
Loaded: loaded (/etc/systemd/system/restart.service; disabled; vendor preset: enabled)
Active: active (running) since Fri 2023-07-23 10:06:05 CST; 10s ago
Main PID: 15651 (demo)
Tasks: 9 (limit: 2262)
Memory: 4.0M
CPU: 15ms
CGroup: /system.slice/restart.service
└─15651 /home/ubuntu/Desktop/test/demo "&!"
4.将restart服务添加到系统启动项中:
sudo systemctl enable restart
然后每次系统启动后,restart服务都会自动启动。