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.)
Comments
Post a Comment