Question

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);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top