简体   繁体   中英

dup2 redirect printf failed?

My code is as follows:

#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;    
}

If I replace the line write(STDOUT_FILENO, msg, strlen(msg)) with printf("%s\\n", msg) , the program can not redirect stdout to file test , what's the reason for this?

Because stdio buffers the output, ie printf("%s\\n", msg) does not immediately write to STDOUT_FILENO .

Add fflush(stdout); before redirecting stdout back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM