在linux系统中有很多方式可以将自定义程序设置成开机自启动,本文所述的方式是通过将程序设置成service来实现自启动。
在/lib/systemd/system目录下新建hello.service文件
touch /lib/systemd/system/hello.service
vi /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
重启系统测试
reboot
查找hello.service的状态
systemctl status hello.service