在網上找了許多資料,發現不同系統下的編寫方法有點不同,這里用的了ubuntu下的方法,供參考:
先寫一下小程序運行 , init_daemon:
1 #include <stdlib.h> 2 #include <stdio.h> 3 4 int main() 5 { 6 daemon(0,0); // 將進程聲明為守護進程 7 8 int i = 0 ; 9 while(1) 10 { 11 i++ ; 12 sleep(100000); 13 } 14 }
編譯,生成可執行文件: gcc -c init_daemon gcc -o init_daemond init_daemon.o ( 這里守護進程一般在文件后面加個d )
下面寫bash文件,注意這個文件名一定要與程序名一致 ,這里文件名為: init_daemond,創建后修改文件屬性為 sudo chmod +x init_daemond :
1 #! /bin/sh 2 3 ### BEGIN INIT INFO 4 # Provides: 5 # Description: A simple example for daemon app 6 ### END INIT INFO 7 8 9 if [ -f /etc/init.d/functions ] 10 then 11 . /etc/init.d/functions 12 else 13 . /lib/lsb/init-functions 14 fi 15 16 NAME=Example_Daemond 17 DAEMON=/usr/bin/init_daemond 18 LOCKFILE=/var/lock/subsys/$DAEMON 19 PIDFILE=/var/run/$NAME.pid 20 21 #start function 22 start(){ 23 echo -n "Starting daemon: "$NAME 24 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON 25 echo "." 26 } 27 #stop function 28 stop(){ 29 echo "Stopping $DAEMON ..." 30 if pidof $DAEMON > /dev/null; then 31 killall -9 $DAEMON > /dev/null 32 rm -rf $PIDFILE 33 echo "Stop $DAEMON Success..." 34 fi 35 } 36 37 38 #restart function 39 restart(){ 40 start 41 stop 42 } 43 44 #status function 45 status(){ 46 if pidof -o %PPID $DAEMON > /dev/null; then 47 echo $NAME" is running..." 48 exit 0 49 else 50 echo $NAME" is not running..." 51 exit 1 52 fi 53 } 54 55 56 case "$1" in 57 start) 58 start 59 ;; 60 stop) 61 stop 62 ;; 63 reload|restart) 64 stop 65 sleep 2 66 start 67 ;; 68 status) 69 status 70 ;; 71 *) 72 echo $"Usage: $0 {start|stop|restart|status}" 73 exit 1 74 esac
然后可以用service 命令啟動守護進程:
1 service init_daemond start 2 service init_daemond stop 3 service init_daemond status
可以用ps -ef 命令來查看守護進程的運行