现在的位置: 首页 > 综合 > 正文

linux下实现自动后台运行,脱离输出到终端

2012年09月09日 ⁄ 综合 ⁄ 共 1370字 ⁄ 字号 评论关闭

看sipp的源代码,看到里面有实现完全后台运行,即脱离了终端。不向终端打印任何信息。

代码如下:

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024

int main(int argc, char *argv[])
{
//	return 0;
        pid_t l_pid;
        switch(l_pid = fork())
        {
            case -1:
                // error when forking !
                printf("Forking error");
                exit(-1);
            case 0:
                // child process - poursuing the execution
                // close all of our file descriptors
                {
                    int nullfd = open("/dev/null", O_RDWR);

                    dup2(nullfd, fileno(stdin));
                    dup2(nullfd, fileno(stdout));
                    dup2(nullfd, fileno(stderr));
                    //sleep(100);

                    close(nullfd);
                }
                break;
            default:
                // parent process - killing the parent - the child get the parent pid
                printf("Background mode - PID=[%d]\n", l_pid);
                exit(1);
        }
                printf("Background mode - PID=[%d]\n", l_pid);
                    sleep(100);
}

关闭了stdin stdout stderr,而父进程在exit(1)处结束,而子进程继续执行下面的sleep等代码。

这里

/dev/null是 

/dev/null看作"黑洞".
它非常等价于一个只写文件. 所有写入它的内容都会永远丢失. 而尝试从它那儿读取内容则什么也读不到. 然而, 
/dev/null对命令行和脚本都非常的有用.

The function fileno() examines the  argument  stream  and  returns  its
       integer descriptor.

dup2 

 dup2() makes newfd be the copy of oldfd, closing newfd first if  neces‐
       sary, but note the following: 

If  oldfd  is  not a valid file descriptor, then the call fails, and
          newfd is not closed.

       *  If oldfd is a valid file descriptor, and newfd has the same value as
          oldfd, then dup2() does nothing, and returns newfd.

解释下:fileno只是读取FILE *或流的int标志。

             dup2 原型是:int dup2(int oldfd, int newfd); 将newfd是oldfd的一个拷贝,如果newfd打开,则先关闭它。


抱歉!评论已关闭.