您的位置:首页 > 运维架构 > Linux

一个linux守护进程的编写(Ubuntu环境下)

2013-05-30 15:35 246 查看
在网上找了许多资料,发现不同系统下的编写方法有点不同,这里用的了ubuntu下的方法,供参考:

先写一下小程序运行 , init_daemon:

#include <stdlib.h>
#include <stdio.h>

int main()
{
daemon(0,0);  // 将进程声明为守护进程

int i = 0 ;
while(1)
{
i++ ;
sleep(100000);
}
}


编译,生成可执行文件: gcc -c init_daemon gcc -o init_daemond init_daemon.o ( 这里守护进程一般在文件后面加个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 命令启动守护进程:

service init_daemond start
service init_daemond stop
service init_daemond status


可以用ps -ef 命令来查看守护进程的运行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: