Search code examples
csocketsstdoutstdiodup2

Redirecting stdout to socket


I am trying to redirect stdout to a socket. I do something like this:

dup2(new_fd, STDOUT_FILENO);

After doing so all stdio functions writing to the stdout fail. I have tried to reopen stdout this way:

fclose(stdout);
stdout = fdopen(STDOUT_FILENO, "wb");

But printf and other functions still don't work.

EDIT:

I am affraid that I misunderstood the problem at the first place. After some more debugging I've figured out that this is a real issue:

printf("Test"); // We get Broken pipe here
// Reconnect new_fd
dup2(new_fd, STDERR_FILENO);
printf("Test"); // This also returns Broken pipe despite that stdout is fine now

Thanks.


Solution

  • I've solved the problem by clearing a stdio's error indicator after fixing stdout:

    clearerr(stdout);
    

    Thanks for your help.