Hacker News new | ask | show | jobs
by spc476 3713 days ago
What you are asking for, "post-redirection" (a term I just coined) is not an easy task. Redirection is, but that's set up prior to the program run (warning: pseudocode ahead):

    child = fork()
    if child == 0 then
      stdout = open("output","w")
      stderr = open("error","w")
      dup2(stdout,FILENO_STDOUT)
      dup2(stderr,FILENO_STDERR)
      Close(stdout)
      Close(stderr)
      Execve("someprogram",arglist,envlist)
    End
Standard Unix stuff. But doing that after the program is running isn't easy. The only way I know of is to send the program SIGSTOP (stops execution of the program---said signal can't be caught), and using ptrace(), inject code into the process to open the output file and call dup2() to get the redirection going, calling said code, then resuming the program.

I suppose one could script gdb (or whatever Unix debugger exists on the suystem) to do such a thing, but the fact that no one has really done this might mean something.