IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Linux Socket 学习笔记23-守护进程inetd

    Qiang发表于 2009-08-10 01:31:40
    love 0

    守护进程inetd的一个优点就是可以简化服务程序代码的编写。例如对TCP服务程序

    序,无需反复编写socket,bind,listen,accept函数调用。

    下面来一个简单的实例。首先,编写代码:

    ?View Code C
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    
    /* inetd_test.c:
    * Example inetd daytime server :
    */
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include types.h><span>
    /*
    * This function reports the error and
    * exits back to the shell :
    */
    static void
    bail(const char *on_what) {
    if ( errno != 0 ) {
    fputs(strerror(errno),stderr);
    fputs(": ",stderr);
    }
    fputs(on_what,stderr);
    fputc('\n',stderr);
    exit(1);
    }
     
    int
    main(int argc,char **argv) {
    int z;
    int n;
    time_t td;        /* Current date&time */
    char dtbuf[128];     /* Date/Time info */
     
    /*
    * Generate a time stamp :
    */
    time(&amp;td);
    n = (int) strftime(dtbuf,sizeof dtbuf,
    "%A %b %d %H:%M:%S %Y\n",
    localtime(&amp;td));
     
    /*
    * Write result back to the client :
    */
    z = write(1,dtbuf,n);
    if ( z == -1 )
    bail("write(2)");
     
    return 0;
    }

    代码确实简单多了。

    然后编译:

    ?View Code BASH
    1
    
    $ gcc inetd_test.c -o inetd_test

    现在就可以通过inet调用它了。

    为了方便,首先将可执行文件复制到/tmp目录下:

    ?View Code BASH
    1
    
    $ cp inetd_test /tmp/inetd_test

    再给它加是执行权限:

    ?View Code BASH
    1
    
    $ chmod a+rx /tmp/inetd_test

    然后修改inet的配置文件inetd.conf:

    ?View Code BASH
    1
    2
    3
    
    $ tail -l /tec/inetd.conf
     
    9999 stream tcp nowait root /tmp/inet_test null

    最后重启inetd进程:

    查找inetd进程的pid:

    ?View Code BASH
    1
    
    $ ps -ax | grep inetd

    例如pid为333,重启:

    ?View Code BASH
    1
    
    $ kill -HUP 333


沪ICP备19023445号-2号
友情链接