dup2重定向printf失败了吗?

Cha*_*429 4 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;    
}
Run Code Online (Sandbox Code Playgroud)

如果我更换线write(STDOUT_FILENO, msg, strlen(msg))printf("%s\n", msg),程序无法重定向stdout到文件test,什么是这个原因?

Mar*_*n R 6

因为stdio 缓冲输出,即printf("%s\n", msg)不立即写入STDOUT_FILENO.

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