anon
anon

Reputation:

Redirect output back to terminal in C

    if (out) {
            out = 0;
            int fd = open(output_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
            if (fd == -1) perror("open for writing");
            if (dup2(fd, STDOUT_FILENO) < 0) { perror("dup2"); abort();}
            close(fd);
    }

    if (-1 == execvp(argv[0], argv)) {
      perror("execvp");
      printf("  (couldn't find command)\n");
    }



    exit(1);

I am trying to redirect output back into terminal after redirecting it to a separate file. At the moment, this works when I call:

$ ls > file.txt

However, when I call

$ ls -l

right afterwards, it continues to direct its output into file.txt, rather than the terminal.

Upvotes: 0

Views: 860

Answers (1)

John Bollinger
John Bollinger

Reputation: 180058

You cannot get the original standard output back after closing all copies of it.

Normally, if you are going to exec another program with redirected output, you first fork() a child, and apply the redirection only in the child, then have the child terminate immediately if the exec fails. The parent's streams are unaffected that way, so there is no need to restore them. This is what shells do when they run external commands.

But to answer the question posed, if you want to be able to redirect the standard output and then later restore it, you need to make a copy of it first ...

int stdout_save = dup(STDOUT_FILENO);

Then perform your redirection. When ready to restore, just copy the saved file descriptor back, and close the dupe.

dup2(stdout_save, STDOUT_FILENO);
close(stdout_save);

Do not neglect to perform proper checks on the return values of these function calls; I have omitted that from the example code for clarity and brevity.

Upvotes: 3

Related Questions