Linuxデーモンプログラム

基本的なデーモンプログラムと実行方法について記述します。多重起動の防止方法などを実装していないため、カスタマイズする必要はある。

Cでのプログラム

下記のプログラムはデーモンプログラムとして実行後、停止(SIGKILL)が呼び出されるまでループし続けるひな形です。

/* メイン処理ループ */部分にデーモンの処理を記述すればよい。

#include <iostream>
#include <signal.h> // signal
#include <sysexits.h> //
using namespace std;volatile sig_atomic_t _sigterm = 0;// SIGTERM発生時の処理
void OnSignalTerm(int sig){
_sigterm = sig;
}

int main() {
if( daemon(0,0) != 0 ){
fprintf(stderr, “daemon error.\n”);
return -1;
}struct sigaction sa;

// SIGTERMのハンドラを設定
sigaction(SIGTERM, (struct sigaction*)NULL, &sa);
sa.sa_handler = OnSignalTerm;
sa.sa_flags = SA_NODEFER;
sigaction(SIGTERM, &sa, (struct sigaction*)NULL);

while(_sigterm == 0 ){
/* メイン処理ループ */

usleep(100 * 1000);
}

return 0;
}

スクリプト

上記C言語のプログラムをコンパイルしたものを、/usr/local/sampleへ保存したと仮定して、起動/停止用のスクリプトを記述する。
スクリプトは/etc/rc.d/init.d/sample へ保存する。
(ファイル名はサービス名と同じにする。)

#!/bin/sh
# sample Daemon script
#
# chkconfig: – 55 45
# description: Starts and stops the sample daemons.
#
# processname: sample
# config: /user/local/sample/sample.conf
# pidfile: /var/run/sample.pid. /etc/rc.d/init.d/functions#起動するデーモン(実行ファイル)のパス
sampled=
${SAMPLED-/usr/local/sample/sampled}
#デーモンのサービス名
prog=“sample”
#コンフィグファイルのパス
config=${CONFIG-/usr/local/sample/sample.conf}
#PIDを格納するファイルのパス
pidfile=${PIDFILE-/var/run/sample.pid}
#ロックファイルへのファイルパス
lockfile=${LOCKFILE-/var/lock/subsys/sample}
#停止時のタイムアウト設定
STOP_TIMEOUT=${STOP_TIMEOUT-10}start() {
echo -n $”Starting $prog: ”
daemon –pidfile=${pidfile} $sampled
RETVAL=$?
[ $RETVAL = 0 ] && touch ${lockfile}
echo
return $RETVAL
}stop() {
echo -n $”Stopping $prog: ”
#killproc -p ${pidfile} -d ${STOP_TIMEOUT} $sampled
killproc -d ${STOP_TIMEOUT} $sampled
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f ${lockfile}
return $RETVAL
}case “$1″ in
start)
start
;;
stop)
stop
;;
status)
status $prog
RETVAL=$?
;;
restart)
stop
start
;;
condrestart)
if [ -f $lockfile ]; then
stop
start
fi
;;
reload)
action $”Reloading $prog: ”
;;
*)
echo $”Usage: $0 {start|stop|restart|reload|condrestart|status}”
exit 1
esac

exit $RETVAL

起動方法

# /etc/rc.d/init.d/sample start
sample を起動中: [OK]
#

停止方法

# /etc/rc.d/init.d/sample stop
sampleを停止中: [OK]
#

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください