The right way to do it is to replace the file descriptors STDIN_FILENO
, STDOUT_FILENO
and STDERR_FILENO
with the opened files using dup2()
. You should also then close the original files in the child process:
else if (pid == 0)
{
dup2(fileno(someopenfile), STDIN_FILENO);
dup2(fileno(someotherfile), STDOUT_FILENO);
dup2(fileno(somethirdopenfile), STDERR_FILENO);
fclose(someopenfile);
fclose(someotheropenfile);
fclose(somethirdopenfile);
execvp(args[0], args);
// handle error ...
}