The extern
variables stdin
, stdout
and stderr
are FILE *
pointers. You can pass these to setbuf
/ setvbuf
. However, note that the child has a separate address space so whilst it will inherit the state of the buffers at the time of the fork()
, both can continue to use the buffers safely, and if you fflush
STDOUT
and STDERR
, the output buffers will be empty anyway.
This is the way I would do it in the child (untested, and please do add some error handling):
void
child ( ... )
{
const char *devnull = "/dev/null";
/* turn off buffering */
setvbuf (stdin, NULL, _IONBF);
setvbuf (stdout, NULL, _IONBF);
setvbuf (stderr, NULL, _IONBF);
for (i = getdtablesize () - 1; i >= 0; i--)
{
if ((i != write_end_of_pipe1) && (i != write_end_of_pipe2))
close (i);
}
i = open (devnull, O_RDWR);
if (i == -1)
{
fprintf (stderr, "Unable to open /dev/null\n");
return;
}
i = open (devnull, O_RDONLY);
if (i != 0)
{
dup2 (i, 0);
close (i);
}
dup2 (write_end_of_pipe1, 1);
close (write_end_of_pipe1);
dup2 (write_end_of_pipe2, 2);
close (write_end_of_pipe2);
return;
}