dup2重定向printf失败了吗?

时间:2014-02-04 14:14:24

标签: c unix

我的代码如下:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char *argv)
{
    int fd;
    int copy_stdout;
    char *msg = "a test message for redirect stdout";

    //open a test file to write message
    fd = open("test", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);

    //copy the original file descriptor 
    copy_stdout = dup(STDOUT_FILENO);

    //redirect the stdout to fd
    dup2(fd, STDOUT_FILENO);

    //must close the fd to complete redirect
    close(fd);

    //write the message
    write(STDOUT_FILENO, msg, strlen(msg));

    //redirect back
    dup2(copy_stdout, STDOUT_FILENO);

    //print the message to stdout
    printf("%s\n", msg);
    return 0;    
}

如果我将行write(STDOUT_FILENO, msg, strlen(msg))替换为printf("%s\n", msg),则该计划无法将stdout重定向到文件test,原因是什么?

1 个答案:

答案 0 :(得分:6)

因为stdio 缓冲输出,即printf("%s\n", msg)没有 立即写信至STDOUT_FILENO

在重新定向stdout之前添加fflush(stdout);