1

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.

4

2 回答 2

1

1: on dup2(src, dst)

A number of operating systems track open files through the use of file descriptors. dup2 internally duplicates a file descriptor from the src to dst, closing dst if its already open.

What your first statement is doing is making every write to STDOUT_FILENO to go to the object represented by new_fd. I say object because it could be a socket as well as a file.

I don't see anything wrong with your first line of code, but I don't know how new_fd is defined.

2: on reopening stdout

When you close a file descriptor, the OS removes it from its table. However, when you open a file descriptor, the OS sets the smallest available file descriptor as the returned value. Thus, to reopen stdout, all you need to do is reopen the device. I believe the device changes depending on the OS. For example, on my Mac the device is /dev/tty.

Therefore, to reopen the stdout, you want to do the following:

close(1);
open("/dev/tty", O_WRONLY);
于 2013-02-27T02:07:59.530 回答
1

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

clearerr(stdout);

Thanks for your help.

于 2013-02-27T15:51:21.893 回答