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

    在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

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值