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


    在网上找了许多资料,发现不同系统下的编写方法有点不同,这里用的了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 命令来查看守护进程的运行

  • 相关阅读:
    unity_动画_状态机
    有内涵的技术论坛
    ios开发——常用经典算法OC篇&冒泡/快速
    iOS开发——C篇&文件操作
    iOS开发——C篇&预处理
    iOS开发——C篇&结构体与枚举
    iOS开发——C篇&函数解析
    iOS开发——C篇&动态内存分析
    UML第二次作业(代码互评)
    我与UML相爱相杀的狗血日常
  • 原文地址:https://www.cnblogs.com/trying/p/3108324.html
Copyright © 2020-2023  润新知