intmain() { int fd, old_stdout; char *filename = "dup2-to-file-output.txt"; // keep the original stdout for restore old_stdout = dup(STDOUT_FILENO); if (old_stdout == -1) { perror("dup failed"); exit(EXIT_FAILURE); } // open the file for writing fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } // redirect stdout to file if (dup2(fd, STDOUT_FILENO) == -1) { perror("dup2 failed"); exit(EXIT_FAILURE); } close(fd); // close fd, because STDOUT_FILENO is now pointing to it // now printf's output will be written to file printf("This text will be written to %s\n", filename); printf("Another line for testing...\n");
// Remember to flush the buffer otherwise the output will be buffered fflush(stdout); // restore original stdout if (dup2(old_stdout, STDOUT_FILENO) == -1) { perror("dup2 restore failed"); exit(EXIT_FAILURE); } // close the backup descriptor close(old_stdout); // after restore, output to terminal printf("Now back to terminal output\n"); return0; }
编译使用的方法如下所示:
1 2 3 4 5 6 7 8
$ gcc -o linux-dup2-to-file linux-dup2-to-file.c
$ ./linux-dup2-to-file Now back to terminal output
$ cat dup2-to-file-output.txt This text will be written to dup2-to-file-output.txt Another line for testing...