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

daemon编程 重定向输出和出错流

2013年07月18日 ⁄ 综合 ⁄ 共 766字 ⁄ 字号 评论关闭
/*
 * 如何重定向一个进程的stderr,stdin,stdout到一个文件
 * 如果文件不存在,则默认重定向到/dev/null
 *
 */

/*
 * 把输入重定向到/dev/null
 * 把标准出错重定向到 指定文件中
 * 因为我们不能确定是否stderr和stdout都正在使用系统默认
 * 的文件描述符,所以最好使用函数fileno(stderr)来对流进行转换。
 */

#define FAIL -1
#define OK 0

void
redirect_std(const char *filename)
{
    int fd;
    const char default_file[] = "/dev/null";   
    const char *out_file = default_file;   
    int open_flags = O_WRONLY;
   
    //把输入定向到/dev/null
    close(fileno(stdin));       
    open(default_file, O_RDONLY);
   
    if(filename && *filename){
        out_file = filename;
        open_flags |= O_CREAT | O_APPEND;
    }
   
    //打开需要重定向到的文件
    if(-1 != (fd = open(filename, open_flags, 0666))){
        if(-1 == dup2(fd, fileno(stdout)))       
            exit(1);
        if(-1 == dup2(fd, fileno(stderr)))
            exit(1);
        close(fd);
    }
    else{
        exit(FAIL);
    }   
}

【上篇】
【下篇】

抱歉!评论已关闭.