Hi,
On Linux, I have some C++ code where I want to execv another application. That program outputs some data to the stderr. I therefore redirect the stderr by calling freopen() with stderr as the stream parameter. The thing is, I want to redirect the stderr for another process that is run.
Here is the scenario I am working with. I fork() the current process; in the child process, I redirect the stderr; then I execv() to run the separate application.
Firstly, I have a Sentry set up to redirect the stderr output. Here is the code:
class StderrSentry {
public:
  StderrSentry() {
    freopen( "NUL", "wt", stderr );
  }
  ~StderrSentry() {
    fclose( stderr );
  }
};
Then later in the code:
pid_t pid = fork();
int retval=-1;
if( pid < 0 ) {
  success = false;
}
else if( ! pid ) {  // child process
  StderrSentry stdErrSentry;   // REDIRECTING STDERR HERE!
  pid_t chid = setsid();
  if (chid == -1 ) {
    exit(-1);
  }
  else {
    //  HERE IS THE execv() call:
    if( execv(command[0].c_str(), const_cast<char**>(&c_args[0])) < 0 ) {
      exit( -1 );
    }
  }
}
// ... else etc...
Will the stderr redirect actually still technically be valid once the execv() call replaces the current process with the specified one?
This is actually behaving as I desire, but is it a fluke, or is this the way to do it?
I cannot activate the stderr redirect in the application that is run in the execv, since it is not my code.
Thanks for any info on this.