首先写一个小程序,模拟常驻进程,简单起见,也就不写什么精灵进程了,就为了实验下。
- #include <stdio.h>
- #include <unistd.h>
- int main(int argc, char *argv[])
- {
- while (1)
- {
- sleep(10);
- printf("hello, world\n");
- }
- return 0;
- }
首先是start函数,新建一个helld的文件,开头的固定格式为:
- # chkconfig: 2345 99 97
- if [ -f /etc/init.d/functions ] ; then
- . /etc/init.d/functions
- elif [ -f /etc/init.d/functions ] ; then
- . /etc/init.d/functions
- else
- exit 1
- fi
- $SERVICE_DIR="."
- $PROC_NAME="hello"
- start()
- {
- for process in $PROC_NAME
- do
- if process_running $process
- then
- echo "$process is already running, exiting..."
- echo_failure
- exit_code=1
- else
- nohup $SERVICE_DIR/$process > /dev/null 2>&1 &
- echo_success
- echo
- fi
- done
- }
- process_running()
- {
- self_pid=$(pidofproc $1)
- if [ -n "$self_pid" ] ; then
- return 0
- else
- return 1
- fi
- }
然后是stop函数:
- stop()
- {
- for process in $PROC_NAME
- do
- killproc $process
- echo
- RETVAL=$?
- return $RETVAL
- done
- }
最后是判断状态的函数,重起个名,叫process_status,避免冲突了
- process_status()
- {
- for process in $PROC_NAME
- do
- if ! status $process
- then
- exit_code=1
- else
- echo_failure
- exit_code=0
- fi
- done
- }
- case "$1" in
- start)
- start
- ;;
- stop)
- stop;;
- restart|reload)
- stop
- sleep 1
- start
- ;;
- status)
- process_status
- ;;
- *)
- echo $"Usate: $0 {start|stop|restart|status}"
- exit_code=1
- ;;
- esac
- exit $exit_code
- mv hellod /etc/init.d
- /sbin/chkconfig --add hellod #通过chkconfig添加一个新的服务
- /sbin/chkconfig hellod on #将这个服务加入开机自启动