I would like to change the file descriptor so that my execvp
commands are sent to a file. Afterwards, I would like to reset stdout
back to the console.
This is what I have so far:
int main() {
printf("to console\n");
int stdoutfd = dup(STDOUT_FILENO);
FILE* file = fopen("./test.txt","ab+");
int filefd = fileno(file);
dup2(filefd,STDOUT_FILENO);
char *args[] = {"ls","-la",NULL};
execvp(args[0],args);
dup2(stdoutfd,STDOUT_FILENO);
close(stdoutfd);
printf("to console\n");
}
The first printf
prints to console, then the execvp on the "ls -la" commands gets printed to the test.txt
file, but my problem is that the second printf
does not print anywhere.
I realize a similar question has been answered at C restore stdout to terminal, but that solution does not seem to work.