c - dup2 重定向 printf 失败?

标签 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;    
}

如果我用 printf("%s\n", msg) 替换 write(STDOUT_FILENO, msg, strlen(msg)) 行,程序不能将 stdout 重定向到文件 test,这是什么原因?

最佳答案

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

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

关于c - dup2 重定向 printf 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21554883/

相关文章:

linux - grep:如何将匹配捕获到变量中?

c - 如何使用C发出警报声?

Ctrl-C 被 getchar() 吃掉

带堆栈和链表的 C 语言计算器

c - 在 linux 中运行特定的 c 文件

linux - 在 Unix 或 Gnu/Linux 上减少进程的权限

unix - 记住代码,专业人士你是怎么做到的

linux - aix/ksh shell 前后的 grep 行

C 编程代码不会停止从文本文件读取

java - 最佳实践 : Where to resample PCM and which tool?