1.将init_daemon放入程序开始处
void init_daemon()
{
int pid;
int i;
if(pid=fork())
exit(0);//是父进程,结束父进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第一子进程,后台继续执行
setsid();//第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if(pid=fork())
exit(0);//是第一子进程,结束第一子进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长
for(i=0;i< NOFILE;++i)//关闭打开的文件描述符
close(i);
//chdir("/tmp");//改变工作目录到/tmp
umask(0);//重设文件创建掩模
return;
}
2.将chefd文件(如下)放进etc/init.d
#!/bin/bash
#
# chef_service This shell script takes care of starting and stopping
# chef_test system.
#
# chkconfig: 35 95 85
# description: chef_test system.
# processname: chef
# config: /usr/local/chef/cfg/chef.xml
# pidfile: /var/run/chef.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network
export MYCOMM_INSTALL_PATH=/usr/local/chef
RETVAL=0
prog="chef_test"
chef_daemon="$MYCOMM_INSTALL_PATH/bin/$prog"
pid_file="/var/run/chef.pid"
start() {
# Start daemons.
echo -n $"Starting $prog: "
daemon $chef_daemon
RETVAL=$?
echo
[ $RETVAL -eq 0 ]
return $RETVAL
}
stop() {
# Stop daemons.
#if test -f $pid_file ; then
echo -n $"Shutting down $prog: "
killproc $prog #-SIGTERM
RETVAL=$?
echo
[ $RETVAL -eq 0 ] #&& rm -f $pid_file
#fi
return $RETVAL
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
RETVAL=$?
;;
status)
status chef_test
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit $RETVAL
3.
cd /etc/init.d
chmod a+x chefd
chkconfig --add chefd
chkconfig --list | grep chefd
4.
service chef start