一、创建守护进的关键步骤:
step 1.创建子进程,父进程退出
step 2.在子进程中创建新会话
step 3.改变当前目录为根目录
step 4.重设文件权限掩码
step 5.关闭文件描述符
实例说明:
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#define MAXFD 64
void demo_init()
{
int i ;
pid_t pid;
if(pid = fork())//fork ,终止父进程
exit(0);
setsid();//为子进程创建新会话期,即摆脱原会话期、原进程组、原控制终端的控制
signal(SIGHUP, SIG_IGN);//父进程对子进程结束状态不感兴趣,忽略子进程结束信号SIG_IGN
chdir("/");// 将当前工作目录改为根目录
umask(0); //文件权限全无
for(i =0 ; i< MAXFD; i++)
{
close(i);//关闭所有打开的文件,包括标准输入/出,错误输出
}
}
int main()
{
demo_init();
while(1);
}
二、Unbuntu 一个linux 守护 编程
先写一下小程序运行 , 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 )
生成的 执行文件拷贝到/usr/bin目录下
在/etc/init.d/ 下面写bash文件,注意这个文件名一定要与程序名一致 ,这里文件名为: init_daemond,创建后修改文件属性为 sudo chmod +x init_daemond :
#! /bin/sh
### BEGIN INIT INFO
# Provides:
# Description: A simple example for daemon app
### END INIT INFO
if [ -f /etc/init.d/functions ]
then
. /etc/init.d/functions
else
. /lib/lsb/init-functions
fi
NAME=Example_Daemond
DAEMON=/usr/bin/init_daemond
LOCKFILE=/var/lock/subsys/$DAEMON
PIDFILE=/var/run/$NAME.pid
#start function
start(){
echo -n "Starting daemon: "$NAME
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON
echo "."
}
#stop function
stop(){
echo "Stopping $DAEMON ..."
if pidof $DAEMON > /dev/null; then
killall -9 $DAEMON > /dev/null
rm -rf $PIDFILE
echo "Stop $DAEMON Success..."
fi
}
#restart function
restart(){
start
stop
}
#status function
status(){
if pidof -o %PPID $DAEMON > /dev/null; then
echo $NAME" is running..."
exit 0
else
echo $NAME" is not running..."
exit 1
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload|restart)
stop
sleep 2
start
;;
status)
status
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
exit 1
esac
然后可以用service 命令启动守护进程:
1 service init_daemond start 2 service init_daemond stop 3 service init_daemond status
可以用ps -ef 命令来查看守护进程的运行