[Unit] Description=Xen documentation viewer [Service] Type=simple User=nobody Group=nobody ExecStart=/usr/bin/python3 -m http.server 9980 WorkingDirectory=/usr/share/doc/xen-doc [Install] WantedBy=multi-user.target
systemd 是個 Linux 上的 init 實做。
init 是整個作業系統上第一個 process,這類程式的可執行檔通常會放在 /sbin/init,執行時 PID 是 1,也是所有其他 process 的 parent process。
在 Linux 上除了 systemd 以外,還有許多其他的 init 實做,例如:
現在已經有許多發行版使用 systemd:
這些是直接在 systemd 自己 (PID = 1) 裡做的事情:
這些是由其他 process 做的事情:
一些可能會由 D-Bus API 叫起來執行的小服務:
這些也是其他 process、或是開機時候執行的東西:
Linux 提供的 cgroup 功能可以將 process 分群管理並設定資源限制。在 systemd 中,每個服務、每個使用者登入,都會放在不同的 cgroup 裡,因此即使某些服務 產生了許多 child process,或是利用 double fork 的技巧讓親子關係變得混亂, 一樣能輕易找出哪些 process 屬於哪些服務。
systemd 設定檔位置:
systemd 常用的小規則:
我相信一定比寫給 SysVinit,放在 /etc/init.d 裡的 shell script 簡單、好讀!
[Unit] Description=Xen documentation viewer [Service] Type=simple User=nobody Group=nobody ExecStart=/usr/bin/python3 -m http.server 9980 WorkingDirectory=/usr/share/doc/xen-doc [Install] WantedBy=multi-user.target
[Unit] Description=No-IP DDNS Service After=network.target [Service] Type=forking ExecStart=/usr/local/bin/noip2 [Install] WantedBy=multi-user.target
[Unit] Description=Netfilter Tables ConditionPathExists=/etc/sysconfig/nftables [Service] Type=oneshot RemainAfterExit=yes ExecStart=/usr/sbin/nft -f /etc/sysconfig/nftables ExecStop=/usr/sbin/nft flush ruleset [Install] WantedBy=basic.target
systemd 不只可以管系統服務,也可以管使用者個人的服務:
systemd 有提供 D-Bus API 給應用程式使用,不用執行 shell script,不用手動 解析指令輸出也能開關服務和查詢服務狀態。