bash シンプルなデーモンプログラムの制御スクリプト

February 21, 2013

Linuxなどで動かすデーモンプログラムを起動(start)・停止(stop)・再起動(restart)・状態確認(status)するための制御スクリプトを書いたのでメモしておく。

実装のポイント
スクリプト
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/bash

prgfile=<Program Script filepath>
pidfile=<PID filepath>

start() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "Daemon has started."
return 1
fi
fi

$prgfile

if [ $? -eq 0 ]; then
echo "Daemon started."
return 0
else
echo "Failed to start daemon."
return 1
fi
}

stop() {
if [ ! -f $pidfile ]; then
echo "Daemon not started."
return 1
fi

pid=`cat $pidfile`
kill $pid >& /dev/null
if [ $? -ne 0 ]; then
echo "Operation not permitted."
return 1
fi

echo -n "Stopping daemon..."
while true
do
kill -0 $pid >& /dev/null
if [ $? -ne 0 ]; then
break
fi

sleep 3
echo -n "."
done

echo -e "\nDaemon stopped."
return 0
}

status() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "Daemon running. (PID: ${pid})"
return 0
else
echo "Daemon might crash. (PID: ${pid} file remains)"
return 1
fi
else
echo "Daemon not started."
return 0
fi
}

restart() {
stop
if [ $? -ne 0 ]; then
return 1
fi

sleep 2

start
return $?
}

case "$1" in
start | stop | status | restart)
$1
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 2
esac

exit $?

停止部分は実行プログラムの性質によって適宜変更すると良い。

Gistにも載せておいた。 https://gist.github.com/tilfin/5004848

Linux

tilfin freelance software engineer