1. 程式人生 > 實用技巧 >Linux Service檔案

Linux Service檔案

從service檔案說起

之前的linux系統,從開機到啟動初始化程序,要經過:

BIOS -> Boot Loader -> 載入系統核心 -> 對核心初始化 -> 啟動初始化程序,提供工作環境

現有的systemd採用了併發啟動機制,提升了開機速度。它將原來的初始化程序改為了systemd管理下的目標.target,並用systemctl來管理服務。

service服務啟動關閉過程

1.設定httpd服務開機啟動
systemctl enable httpd

返回資訊
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.


可以看到這裡是在/etc/下那個目錄建立了一個軟連結(symbolic link)從/usr/lib/...裡,沒說反,下面有驗證

2.檢視服務狀態
systemctl status httpd

返回資訊
Active:inactive(dead)

3.啟動服務
systemctl start httpd

狀態更新為
active (running)
相比之前還多了

Main PID:1079(httpd)
  status:"Processing requests..."
   Tasks:6
  Memory:2.9M
  CGroup:...(每個httpd化程序佔用的埠號和狀態)

4.停止httpd服務
systemctl stop httpd.service

再次檢視status變回inactive了

● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Sat 2020-07-25 09:23:48 CST; 2s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 3578 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
  Process: 1079 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=0/SUCCESS)
 Main PID: 1079 (code=exited, status=0/SUCCESS)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"

如果停不下來了,用kill殺掉
systemctl kill httpd.service

5.前面設定了開機啟動,現在把它關掉
systemctl disable httpd

返回結果
Removed symlink /etc/systemd/system/multi-user.target.wants/httpd.service.
就是把建立的軟連結刪除了

6.[.server]檔案裡面是什麼
cat httpd.server

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target    啟動順序
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd    讀取自己的環境引數
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND    啟動程序時執行的命令
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful    $OPTIONS來自上面環境引數檔案
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target    表示httpd服務所在的Target(服務組)

它分為3個模組:
[Unit]是啟動順序和依賴關係,如果有Wants或Requires欄位代表依賴關係
[Service]是啟動的行為
[install]是如何安裝這個配置檔案

.server檔案還有很多東西,這裡就針對httpd說一下,剩下的遇到了再研究

驗證:檢視下步驟1.enable裡的目錄
插一句,簡單說下軟連結的建立
ln -s file file_ln
-s 建立軟連結 沒有這個引數就是建立硬連結

接下來先去看下它操作的.service檔案

cd /etc/systemd/system/multi-user.target.wants
ll

顯示為lrwxrwxrwx的連結檔案,原檔案在/usr/lib/systemd/system/裡
再到/usr/lib/systemd/system/裡,找到了httpd.service
-rw-r--r-- 1 root root 752 Nov 27 2019 httpd.service

參考部落格
https://blog.csdn.net/Mr_Yang__/article/details/84133783Centos7之Systemd(Service檔案)詳解