C dup2重定向printf失败?

C dup2重定向printf失败?,c,unix,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 cop

我的代码如下:

#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;    
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv)
{
int-fd;
int copy_stdout;
char*msg=“重定向标准输出的测试消息”;
//打开测试文件以写入消息
fd=开放(“测试”,O|u创建| O|u RDWR,S|u IREAD | S|IWRITE);
//复制原始文件描述符
复制\u stdout=dup(stdout\u文件号);
//将标准输出重定向到fd
dup2(fd,标准文件号);
//必须关闭fd才能完成重定向
关闭(fd);
//写下信息
写入(STDOUT_文件号、msg、strlen(msg));
//重定向回
dup2(复制标准件、标准件文件号);
//将消息打印到标准输出
printf(“%s\n”,msg);
返回0;
}
如果我将行
write(STDOUT\u FILENO,msg,strlen(msg))
替换为
printf(“%s\n”,msg)
,程序无法将
STDOUT
重定向到文件
test
,原因是什么?

因为stdio缓冲输出,即
printf(“%s\n”,msg)
立即写入
STDOUT\u FILENO

添加
fflush(标准输出)在重定向回标准输出之前