如何使用「service」指令而不是「/etc/init.d/nameofservice start」來啟動和停止服務?

如何使用「service」指令而不是「/etc/init.d/nameofservice start」來啟動和停止服務?

我正在使用以下命令啟動服務(httpd):

/etc/init.d/'name of service' start

如果上面的 httpd 服務沒有設定 service 關鍵字,如何使用下面的指令啟動服務?

2)服務'nameofservice'啟動例如:service httpd start

如何設定可以使用服務關鍵字啟動和停止的服務,即:「service 'nameofservice' start」(如選項 2 中的服務關鍵字)而不是 /etc/init.d/nameofservice?

答案1

service(8) 指令在 /etc/init.d 中尋找腳本。如果不存在這樣的腳本,您可能需要編寫自己的腳本。在網路上你可以找到指南將幫助您做到這一點

答案2

下面的腳本在 Centos 5 中進行了測試。

vim /opt/timed     


 #!/bin/bash 
while true;do
      echo  `date` >> /tmp/timed.log 
done #script finish here below line enable execute permission of script

 chmod +x /opt/timed

現在我們將編寫 System V 腳本來啟動和停止定時腳本。

vim /etc/init.d/time (save the script only in /etc/init.d directory only with the name of your choice we use name time here)


  #!/bin/bash  
  # chkconfig: 345 80 20      
  # description: startup script for /opt/timed daemon  
start() {  
nohup /opt/timed &  
}  
stop() {  
pkill timed  
}  
case "$1" in  
             start)   
                   start  #calling the start () function  
             ;;  
             stop)  
                   stop # calling the stop() function
             ;;  
             *)
                   echo "Usage: $0 {start|stop}"  
                   RETVAL=1 #we return the value 1 bcz cmd is not sucessfull  
  esac
  exit 0



 chmod +x /etc/init.d/time  (enabling the execute permission of script)
 service time start    (it will start the script timed)
 ps –ef | grep timed (we can check that script is running with this command)

腳本說明

時間腳本必須在該/etc/init.d目錄中。chkconfig: 345 80 20是腳本 345 的必要組成部分,代表 3,4 和 5 運行等級。 20 表示啟動指令在 /etc/rc3/ 目錄中的編號為 20 (S20)。 80 表示 stop 指令將在 /etc/rc3/ 目錄中包含數字 80 (k80)。

start()stop()是用於啟動和停止守護程序的函數。當您在背景執行 Unix 作業(使用 &、bg 命令)並從會話登出時,您的程序將會終止。您可以使用多種方法來避免這種情況 - 使用 nohup 執行作業,或使用 at、batch 或 cron 命令將其作為批次作業。 PKill 指令可讓您只需指定名稱即可終止程式。 $1 採用第一個參數。 $0 表示腳本的名稱。 RETVAL是環境變量,相當於腳本的退出狀態,為0表示腳本運行成功,為1表示腳本運行失敗。如果我們指定啟動或停止以外的命令,則會列印使用訊息。

相關內容