soccerkid619
soccerkid619

Reputation: 3

Redirect STDOUT and STDERR to file ">&"

I've coded this up and I'm unsure how to get this to work any other way. I would also appreciate example code of how to test its correctness.

Thanks for the help

dup2(STDOUT_FILENO, STDERR_FILENO);
dup2(fd, STDOUT_FILENO);

Upvotes: 0

Views: 543

Answers (1)

Barmar
Barmar

Reputation: 782785

You were close, but you need to do the two dup2 calls in the opposite order.

dup2(fd, STDOUT_FILENO);
dup2(STDOUT_FILENO, STDERR_FILENO);
close(fd);

Your code is equivalent to the POSIX shell syntax (which is available in all shells whose syntax is based on Bourne shell):

2>&1 >filename

which makes stderr go to the old stdout while redirecting stdout to the file.

Upvotes: 2

Related Questions