linux程序後臺調度代碼寫法(沒有終端)

 /* 該段代碼要在進程的開寫,不然close那裏可能出異常 */

int  initprocess( const char * workdir)
{

 int  i;
 pid_t pid;

if ( (pid = fork()) < 0)
  return (-1);
 else if (pid)
  _exit(0);   /* parent terminates */

 /* child 1 continues... */

 if (setsid() < 0)   /* become session leader */
  return (-1);

 

if( signal( SIGHUP,  SIG_IGN ) != SIG_ERR )
 {
 }

 if( signal( SIGPIPE, SIG_IGN ) != SIG_ERR )
 {
 }
 if( signal( SIGALRM, SIG_IGN ) != SIG_ERR )
 {
 }
 if( signal( SIGCHLD, SIG_IGN ) != SIG_ERR )
 {
 }

if ( (pid = fork()) < 0)
  return (-1);
 else if (pid)
  _exit(0);   /* child 1 terminates */

 /* child 2 continues... */

 if( NULL != workdir ) chdir( workdir );  /* change working directory */

 /* close off file descriptors */
 for (i = 0; i < 64; i++)
  close(i);

 

/* redirect stdin, stdout, and stderr to /dev/null */
 open("/dev/null", O_RDONLY);
 open("/dev/null", O_RDWR);
 open("/dev/null", O_RDWR);

 return (0);    /* success */
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章