I have the following code:
pid_t pid = fork();
if (pid == -1)
{
// ...
}
else if (pid == 0)
{
stdin = someopenfile;
stdout = someotherfile;
stderr = somethirdopenfile;
execvp(args[0], args);
// handle error ...
}
else
{
// ...
}
The problem is, the input/output of the execvp()
call is still the console, rather than the files. Clearly I am doing something wrong, what is the right way to do this?
Take a look at
freopen
function.I had to do something similar with
stdout
and wrote two functions that do the work for me:The right way to do it is to replace the file descriptors
STDIN_FILENO
,STDOUT_FILENO
andSTDERR_FILENO
with the opened files usingdup2()
. You should also then close the original files in the child process:You can use this when stdin , stdout , stderr are terminal-