设置步骤

在/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

systemctl service 文件配置更多详细信息可参考https://www.freedesktop.org/software/systemd/man/systemd.service.html 

这里注意一点,当系统服务的进程是在ExecStart的程序中完成时,选用Type=simple配置,如果ExecStart的程序有子进程在后台运行时,应该使用Type=forking配置,父进程退出时,子进程也能够在后台运行。

新建启动脚本文件hello.sh并加可执行权限

touch /usr/bin/hello.sh
vi /usr/bin/hello.sh


#!/bin/bash
                 
echo "Hello World!"


chmod +x /usr/bin/hello.sh

重启systemctl系统服务和允许hello.service

systemctl daemon-reload
systemctl enable hello.service


测试方法

重启系统

reboot


查找hello.service的状态

systemctl status hello.service


    hello.service - Hello Service
   Loaded: loaded (/lib/systemd/system/hello.service; enabled; vendor preset: en
abled)
   Active: inactive (dead) since Fri 2017-07-28 15:53:48 UTC; 36min ago
  Process: 186 ExecStart=/usr/bin/hello.sh (code=exited, status=0/SUCCESS)
 Main PID: 186 (code=exited, status=0/SUCCESS)

Jul 28 15:53:48 phyboard-mira-imx6-3 systemd[1]: Started Hello Service.
Jul 28 15:53:48 phyboard-mira-imx6-3 hello.sh[186]: Hello World!


如果要启动的是一个脚本,在status中看到说 Exec format Error,则是因为被执行的脚本没有加头部,也就是 

#!/bin/bash

查看服务的打印输出

请使用journalctl,具体使用方法请查看其文档。

journalctl -f -u hello.service