c++ - Redirect FROM stderr to another file descriptor -


my program calls library functions print stderr. want intervene write calls file descriptor #2 instead sent somewhere else.

here first attempt:

bool redirect_stderr (int fd) {     return dup2 (2, fd) > 0; } 

here, fd obtained open("/foo/bar",o_append|o_creat)

after function returns true, std::cerr<<"blah" goes terminal , not file.

what doing wrong?

thanks.

update

thanks, larsmans, i'm not there yet...

void redirect_stderr_to (const char * output_file) {     int fd = open (output_file, o_append | o_creat, s_irusr | s_iwusr);      if (fd < 0) {         throw runtime_error;     }     else {         if (-1 == dup2 (fd, stderr_fileno))             throw runtime_error;          std :: cout << (std::cerr ? "fine\n" : "bad\n");         char x [100];         std :: cerr             << "output " << getcwd (x, 100) << " / " << output_file             <<  " yields " << fd << " errno: " << errno << "\n";         std :: cout << (std::cerr ? "fine\n" : "bad\n");     } } 

this outputs

fine bad 

to stdout , given file empty. (it correctly created if doesn't exist.)

you reversed arguments: it's

dup2(from_fd, to_fd) 

i.e.

dup2(fd, 2) 

(see posix.2008 or manpages.)


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -