Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2035177
  • 博文数量: 414
  • 博客积分: 10312
  • 博客等级: 上将
  • 技术积分: 4921
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-31 01:49
文章分类

全部博文(414)

文章存档

2011年(1)

2010年(29)

2009年(82)

2008年(301)

2007年(1)

分类: C/C++

2010-07-04 02:53:33

方法一: 使用传统的fork()函数。

示例代码如下:

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

// change working directory, this step is optional

   chdir( "/tmp" );

   //parent terminates

  if ( 0 != fork() )  exit( EXIT_SUCCESS );}

  /* first child continues become session leader */
  setsid();
  Signal( SIGHUP, SIG_IGN );
  
  //first child terminates
  if ( 0 != Fork() ) 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下运行,那就完全兼容。

方法三:使用nohup

  如果在退出远程终端“进程不退出”,那么需要的也许只是处理一下SIGHUP。
  使用命令:
     nohup yourCommand &

阅读(835) | 评论(0) | 转发(0) |
0

上一篇:POSIXThreads Programming

下一篇:fopen(), fopen64()

给主人留下些什么吧!~~