daemon
daemon-0.2
該存儲庫包含用於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守護程序運行,但是這樣的守護程序沒有一些不錯的功能,例如Reloadin Configure Files,Roging等。此存儲庫和來源可以幫助您了解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守護程序。但這不是現在的方式,現在如何開始。某些初始腳本或服務文件用於此目的。
使用SystemD使用Linux發行版時,您可以嘗試使用
systemctl start simple-daemon
systemctl status simple-daemon
systemctl reload simple-daemon
systemctl stop simple-daemon
注意:使用
make installcommand在安裝期間,將單元文件simple-daemon.service和forking-daemon.service複製到目錄/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