CentOS6和CentOS7服務開機啟動


CentOS 6和CentOS 7都可以定義開機啟動哪些服務,但CentOS 6的命令是chkconfig,CentOS 7是systemctl。

本文將介紹兩種命令的實現方式。

一、CentOS 6的服務

在CentOS 6下編寫一個服務http,位於/etc/init.d目錄下,具體的腳本如下:

#!/bin/bash
# chkconfig: 2345 10 90 
# description: http ....

start() {
  echo "HTTP is enabled now"
}
stop() {
  echo "HTTP is disable now"
}
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  start
  stop
  ;;
*)
  echo "USAGE $0 {start|stop|restart}"
  exit
esac

注意,兩個注釋"# chkconfig: 2345 10 90"和 "# description: http ...."表示:啟動的level和優先級,已經服務的描述。這兩段注釋是一定要加上的。否則服務添加是報錯。

通過如下命令實現把服務注冊到chkconfig中:

chkconfig --add http

然后可以通過:

chkconfig http on

定義開機啟動這個服務。另外可以查看chkconfig的狀態:

chkconfig --list

 

 

二、CentOS 7的服務

在CentOS 7的機器中創建一個服務的腳本: /etc/init.d/myuptime。具體的腳本如下:

#!/bin/bash

start() {
  echo starting
  while true
  do
    uptime >> /root/myuptime.txt
    sleep 2
  done
}
stop() {
  echo stoping
  pid=`ps -ef | grep myuptime | grep -v grep | awk '{print $2}'`
  kill $pid &
}
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
*)
  echo "USAGE $0 {start|stop|restart}"
  exit
esac

在/etc/systemd/system中創建服務描述文件myuptime.service

[Unit]
Description=uptime Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/etc/init.d/myuptime start
ExecStop=/etc/init.d/myuptime stop

[Install]
WantedBy=multi-user.target

這個文件中包含Unit、Service和Install三個部分。定義了描述、服務屬性的類型和安裝參數等。其中ExecStart、ExecStop定義了啟動和停止的實現方式。

配置好后,運行:

[root@hwcentos70-01 system]#systemctl enable myuptime

ln -s '/etc/systemd/system/myuptime.service' '/etc/systemd/system/multi-user.target.wants/myuptime.service'

systemctl把myuptime服務加入到了啟動項目中。

執行:

[root@hwcentos70-01 system]#systemctl start myuptime

查看:

[root@hwcentos70-01 system]#systemctl status myuptime

myuptime.service - uptime Service

Loaded: loaded (/etc/systemd/system/myuptime.service; enabled)

Active: active (running) since Fri 2016-02-26 13:37:23 UTC; 10s ago

Main PID: 53620 (myuptime)

CGroup: /system.slice/myuptime.service

├─53620 /bin/bash /etc/init.d/myuptime start

└─53632 sleep 2

 

Feb 26 13:37:23 hwcentos70-01 systemd[1]: Started uptime Service.

Feb 26 13:37:23 hwcentos70-01 myuptime[53620]: starting

通過以上的方法實現把myuptime作為服務加入啟動項。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM