• 编写服务单元文件
    创建一个新的服务单元文件通常在 /etc/systemd/system/ 目录下,文件扩展名为 .service。例如,你可以创建一个名为 my_service.service 的文件。
1
2
3
4
5
6
7
8
9
10
11
12
[Unit]
Description=My custom service #描述服务的简短描述
After=network.target # 定义服务启动顺序

[Service]
Type=simple # 服务类型,可以是 simple、forking、oneshot 等
ExecStart=/path/to/your_executable # 启动服务的命令
Restart=always # 服务退出时是否自动重启

[Install]
WantedBy=multi-user.target # 指定服务启动时机

  • 启动服务
1
2
sudo systemctl daemon-reload
sudo systemctl start my_service.service
  • 设置服务为开机自启动
1
sudo systemctl enable my_service.service
  • 检查服务状态
1
sudo systemctl status my_service.service
  • 停止和禁用服务
1
2
sudo systemctl stop my_service.service
sudo systemctl disable my_service.service
  • 查询服务
1
2
3
sudo systemctl list-units --type=service
sudo systemctl list-units --type=service --state=running
sudo systemctl list-unit-files --type=service --state=enabled