zoukankan      html  css  js  c++  java
  • [linux] 创建daemon进程



    方法一:
     使用传统的fork()函数。示例代码如下:

    static void daemon_init ( const char *workdir, mode_t mask )
    {
    int i, j;

    /*
    * change working directory, this step is optional
    */
    chdir( "/tmp" );
    if ( 0 != Fork() )
    {
    /*
    * parent terminates
    */
    exit( EXIT_SUCCESS );
    }
    /*
    * first child continues
    *
    * become session leader
    */
    setsid();
    Signal( SIGHUP, SIG_IGN );
    if ( 0 != Fork() )
    {
    /*
    * first child terminates
    */
    exit( EXIT_SUCCESS );
    }
    /*
    * second child continues
    *
    * change working directory, chdir( "/" )
    */
    chdir( workdir );
    /*
    * clear our file mode creation mask, umask( 0 )
    */
    umask( mask );
    j = Open( "/dev/null", O_RDWR );
    Dup2( j, 0 );
    Dup2( j, 1 );
    Dup2( j, 2 );
    j = getdtablesize();
    for ( i = 3; i < j; i++ )
    {
    close( i );
    }
    return;
    } /* end of daemon_init */

    方法二:
    调用daemon()函数。示例代码如下:

    daemon(1, 0);

    有些系统不支持daemon函数。不过如果你的程序只在linux下运行,那就没问题。

    补充:
    如果你只是想在退出telnet或者putty的时候“进程不退出”,那么你需要的也许只是处理一下SIGHUP。
  • 相关阅读:
    返回三级联动的JSON数据
    返回三级联动的JSON数据
    python3访问map
    第十八讲、中介者模式
    第十七讲、命令模式
    第十六讲、模板方法模式
    第十五讲、组合模式
    第十四讲、享元模式
    第十三讲、装饰器模式
    第十二讲、桥接模式
  • 原文地址:https://www.cnblogs.com/hehe520/p/6330444.html
Copyright © 2011-2022 走看看