Question

On Linux, the stdout (fd 1) output stream is buffered and stderr (fd 2) is not.

Say I do something like this:


int main() {
    close(2);
    open( "newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600 );
    fprintf(stderr, "This is in the text file!");
    fflush(stderr);  //does this do anything? is it needed?
    return 0;
}

If I remember correctly, open uses the lowest available file descriptor, which should be 2 (used to be stderr before the close statement). Since stderr is not buffered, will newfile.txt not be buffered as well? Or does it not matter that fd 2 used to be used for stderr?

Was it helpful?

Solution

You don't actually do anything with stderr so it's status and buffering is unchanged. All you do is change the underlying file descriptor (if the open call doesn't fail of course).


The same behavior can be had by saving the returned file descriptor from open and using dup, or dup2 if you don't close the old file descriptor. I would actually recommend using dup2 instead, as it's more explicit and easier to follow what's happening:

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

int main(void) {
    int fd = open( "newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600 );
    if (fd == -1) {
        perror("open");
        return EXIT_FAILURE;
    }

    if (dup2(STDERR_FILENO, fd) == -1) {
        perror("dup2");
        return EXIT_FAILURE;
    }

    fprintf(stderr, "This is in the text file!");

    return EXIT_SUCCESS;
}

OTHER TIPS

I think your code will most likely seg fault since fflush() expects a FILE* not Unix file descriptor.

fprintf() buffers the output. It doesn't know any different since the file descriptor hasn't changed as far as it is concerned, so fflush() is still needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top