编写 systemd 脚本

vik*_*mun 3 boot init systemd 16.04

我有一个需要在启动时运行的进程。它需要在机器运行的整个时间内保持运行。到目前为止,我只是在 bash 中键入以下内容,然后启动我的服务器。

command -f argument & disown
Run Code Online (Sandbox Code Playgroud)

我知道我需要制作一个 init 脚本,但我不知道怎么做。经过一些研究,似乎 Ubuntu 使用 systemd(一些参考资料说 Upstart,它们不一样吧?)作为它的 init 系统。但是我在网上找到的所有指南都告诉我将可执行文件放在/etc/init/etc/init.d. Init 应该是一个完全不同的 init 系统。

有人可以指出我正确的方向吗?示例 systemd 脚本甚至在线指南都会有很大帮助。

Geo*_*sen 5

你需要两个文件:

  1. 你的脚本文件:

    command.sh
    
    Run Code Online (Sandbox Code Playgroud)
  2. .service文件被放置在/etc/systemd/system与给定的权限644chmod 664 command.service

    command.service
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最简单的内容command.service是:

    [Unit]
    Description=Some service description
    
    [Service]
    ExecStart=/bin/bash -c "/path/to/command.sh -f argument & disown"
    
    [Install]
    WantedBy=multi-user.target
    
    Run Code Online (Sandbox Code Playgroud)
  4. 现在让它在启动时启动,我们使用systemd控制器systemctl

    sudo systemctl enable command
    
    # or 
    
    sudo systemctl enable command.service
    
    Run Code Online (Sandbox Code Playgroud)

请注意,各个部分还有更多选项可用,请参见此处,并确保您command.sh可以通过以下方式执行chmod +x command.sh

  • 不需要包含“&”和“disown”,因为 systemd 已经在后台运行该命令,它不会附加到 shell 会话。查看 `man systemd.service` 以确认 `Type=` 适合您的服务。然后,由于您不需要“&”和“disown”,您应该能够直接执行命令,而不是通过 Bash。 (3认同)