このリポジトリには、Linux OS用のデーモンの簡単な例が含まれています。このリポジトリには、スクリプトを開始する例も含まれています。
超シンプルなデーモンを作成したいときは、とても簡単です。このようなものをCで書いて、それをdaemon.cと呼ぶことができます:
/* Compile this with gcc -o daemon daemon.c */
#include <unistd.h>
int main ( void )
{
while ( 1 ) {
/* TODO: do something usefull here ;-) */
sleep ( 1 );
}
}そして、 simple-daemon.serviceと呼ばれるいくつかの超シンプルなSystemDサービスファイルを書きます:
[Unit]
Description=Super simple daemon
[Service]
Type=simple
ExecStart=/usr/bin/daemon
[Install]
WantedBy=multi-user.target
そして、それをUnixデーモンとして実行することができますが、そのようなデーモンには、リロアディンの構成ファイル、ログなどの素晴らしい機能がありません。このリポジトリとソースは、UNIX Daemonsの仕組みを理解するのに役立ちます。
デーモンの例を作成するには、次のツールを持たなければなりません
デーモンの例を作成するには、次のコマンドを入力する必要があります。
git clone https://github.com/jirihnidek/daemon.git
cd daemon
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr ../
make
sudo make install
コマンドラインからの実行中のデーモンをテストできます。
./bin/daemon
しかし、このようにアプリを実行することは、デーモンを実行することではありません。コマンドラインのパラメーターと引数を見てみましょう
Usage: ./bin/daemon [OPTIONS]
Options:
-h --help Print this help
-c --conf_file filename Read configuration from the file
-t --test_conf filename Test configuration file
-l --log_file filename Write logs to the file
-d --daemon Daemonize this application
-p --pid_file filename PID file used by daemonized app
パラメーター--daemonまたは-dを使用して./bin/daemon実行すると、実際のUnixデーモンになります。しかし、これは方法ではなく、Unix Daemonsが今日どのように開始されているかです。この目的には、一部のinitスクリプトまたはサービスファイルが使用されます。
SystemDを使用してLinux Distributionを使用するときは、Daemonを使用して開始することができます
systemctl start simple-daemon
systemctl status simple-daemon
systemctl reload simple-daemon
systemctl stop simple-daemon
注:ユニットファイル
simple-daemon.serviceおよびforking-daemon.service、make installコマンドを使用してインストール中にディレクトリ/usr/lib/systemd/systemにコピーされます。
Redhat 4/5/6またはCentosを使用する場合、initスクリプトを使用してみることができます。
cp daemon.init /etc/rc.d/init.d/daemond
次に、次のことを使用してデーモンを制御することができるはずです
service daemon start
service daemon status
service daemon reload
service daemon stop