[英]How can I detect if my upstart script is running?
在偽代碼中,我正在嘗試執行以下操作
if myService is running
restart myService
else
start myService
如何將以上內容轉換為bash腳本或類似內容?
標准方法是使用PID文件存儲服務的PID。 然后,您可以使用存儲在PID文件中的PID來查看服務是否已在運行。
查看/etc/init.d
目錄下的各種腳本,並查看它們如何使用PID文件。 還要在大多數Linux系統中的/var/run
下查看一下PID文件的存儲位置。
您可以執行以下操作,這是對所有Bourne shell類型的shell處理此問題的通用方法:
# Does the PID file exist?
if [ -f "$PID_FILE" ]
then
# PID File does exist. Is that process still running?
if ps -p `cat $PID_FILE` > /dev/null 2&1
then
# Process is running. Do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
else
# Process isn't' running. Do a start
/etc/init.d/myService start
cat $! > $PID_FILE
else
# No PID file to begin with, do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
fi
但是,在Linux上,您可以利用pgrep :
if pgrep myService > /dev/null 2>&1
then
restart service
else
start service
fi
請注意如何不使用任何大括號。 if
語句對pgrep
命令的退出狀態pgrep
。 我同時將STDOUT和STDERR輸出到/ dev / null,因為我不想打印它們。 我只想要pgrep
命令本身的退出狀態。
閱讀PGREP上的手冊
有很多選擇。 例如,您可能想使用-x
來防止意外的匹配,或者您可能必須使用-f
來匹配用於啟動服務的完整命令行。
如果在運行ps aux時看到myService ,則可以簡單地在bash中執行此操作(如jordanm所建議使用pgrep進行編輯):
if [ $(pgrep myService) ]; then
restart myService;
else
start myService;
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.