2015年3月10日 星期二

[C] Put the program into background


/* Try to fork */
if (fork_m) {
   switch (pid = fork()) {
     case 0:                    /* Child */

        setsid();               /* Become session leader */
        chdir("/");             /* Don't hold on to current dir */

        {                       /* Close all file descriptors */
                int fd = 0;
                int maxfd = open_max();  /* OPEN_MAX is the constant that defines the maximum number of open files allowed for a single program. */
                while (fd < maxfd) close(fd++);
        }
        /* New descriptors for stdin, stdout & stderr */
        open("/dev/null",O_RDWR);
        dup(0); dup(0);

        break;
     case -1:
        printf("Couldn't run in background, exiting...\n");
        exit(1);
     default:                   /* Parent */
        /* printf("Running in background...%d\n",(int) pid); */
        exit(0);
   }
}


Reference:
1. The source code of ipband

Related Posts:

0 意見:

張貼留言