linux 将自定义程序做成服务开机自启动

在 linux 系统中有很多方式可以将自定义程序设置成开机自启动,本文所述的方式是通过将程序设置成 service 来实现自启动。
在 /lib/systemd/system 目录下新建 hello.service 文件

touch /lib/systemd/system/hello.service
vim /lib/systemd/system/hello.service
[Unit]
Description=Hello Service
 
[Service]
Type=simple
ExecStart=/usr/bin/hello.sh
SuccessExitStatus=2
 
[Install]
WantedBy=multi-user.target

这里注意一点,当系统服务的进程是在 ExecStart 的程序中完成时,选用 Type=simple 配置,如果 ExecStart 的程序有子进程在后台运行时,应该使用 Type=forking 配置,父进程退出时,子进程也能够在后台运行。
新建启动脚本文件 hello.sh 并加可执行权限。

touch /usr/bin/hello.sh
vi /usr/bin/hello.sh
#!/bin/bash

echo "Hello World!" > /home/root/hello
chmod +x /usr/bin/hello.sh
systemctl daemon-reload
systemctl enable hello.service

注意,除了使用 systemctl 命令来设置服务以外,还可以使用软链接 ln 命令来设置

cd /etc/systemd/system/multi-user.target.wants
ln -s /lib/systemd/system/hello.service hello.service
posted @ 2025-01-20 14:40  Thousand_Mesh  阅读(234)  评论(0)    收藏  举报