2

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.

Community
  • 1
  • 1
dinamix
  • 651
  • 8
  • 22
  • 4
    `execvp` does not return on success. `execvp` "replaces the current process image with a new process image". That is, unless there is an error with the `execvp` call, none of the code after the `execvp` will ever execute. You probably want to `fork` first before calling `execvp`. – kaylum Sep 30 '16 at 02:28
  • Have you worked out why that other answer doesn't work? It gives solid advice (and mine isn't the accepted answer). It will work if your program is sane — the example in the question has no `fork()` so there is nothing executed after a successful `execvp()`. The last three lines are never executed if the `execvp()` works. You could change the `"ls"` string into `"not-the-ls"` (assuming you don't have a command called `not-the-ls`, of course) and rerun; then you'd see the `to console` message. – Jonathan Leffler Sep 30 '16 at 02:34
  • Correct; the only time any of the `exec*()` family of function returns is when it has failed to execute whatever it was asked to execute. – Jonathan Leffler Sep 30 '16 at 03:38

2 Answers2

2

There is no afterwards. The execvp function call replaces your process. If it succeeds, the rest of your code does not execute.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

regarding re-assigning stdout to go to a different location

This is from: http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c

Why use freopen()? The C89 specification has the answer in one of the endnotes for the section on :

116. The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

freopen is commonly misused, e.g. stdin = freopen("newin", "r", stdin);. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");. Both expressions attempt to assign to stdin, which is not guaranteed to be assignable.

The right way to use freopen is to omit the assignment: freopen("newin", "r", stdin);

user3629249
  • 16,402
  • 1
  • 16
  • 17