1

I wrote a program that redirects IO of a child process. The problem I'm having is that the new stdout and stderr aren't writing straight to file, they're buffering in memory instead. I tried to fix this, with setvbuf, but have had no luck.

I'm getting no errors with the return of the function.

This is pretty frustrating because I had removed buffering in a previous implementation, but I lost the files somehow. In any case, I'm not sure why setvbuf isn't fixing my issue.

if (!freopen(DBGD_CHILD_STDOUT, "w", stdout)){
    perror ("Couldn't open new child-stdout");
    exit (-1);
}

if (!freopen(DBGD_CHILD_STDERR, "w", stderr)){
    perror ("Couldn't open new parent-stderr");
    exit (-1);
}

if (setvbuf (stdout, 0, _IONBF, 0)){
    perror ("Couldn't change buffering mode of stdout");
    exit (-1);
}

if (setvbuf (stderr, 0, _IONBF, 0)){
    perror ("Couldn't change buffering mode of stderr");
    exit (-1);
}

if (execv (ProcessArgs[0], &ProcessArgs[1]) < 0){
    perror ("Couldn't execute process");
    exit (-1);
}
tay10r
  • 4,234
  • 2
  • 24
  • 44
  • 2
    Maybe this will help: http://stackoverflow.com/questions/2055918/forcing-a-program-to-flush-its-standard-output-when-redirected – Michael Burr May 24 '13 at 08:42
  • thanks. I'll show an implementation without setvbuf, that I had tried previously. – tay10r May 24 '13 at 08:45
  • @Michael actually, I may try using a pseudo terminal - as that question has brought up. Let me look more into it – tay10r May 24 '13 at 08:50
  • can you post all your code? – 0x90 May 24 '13 at 09:16
  • I can tomorrow morning. Basically from the entry point: there is a fork(), chdir(), and a call to pipe() and dup2() (for stdin) and then the code above. I can give more feedback when I wake up tomorrow – tay10r May 24 '13 at 09:26

1 Answers1

0

It is hard to tell what really happens from your description and the small code chunk.

However, the attempts to change buffering before execv will have no effect, as the process will be replaced as a whole, including libc stdio state. You need to change buffering in the executed child process instead.

If you don't control the child, then you can execute it with stdbuf.

spbnick
  • 5,025
  • 1
  • 17
  • 22