通過dup,dup(2)保存標准輸入輸出文件描述符,關閉之后,再通過保存的文件描述符恢復標准輸入輸出符。
- linux下標准輸入輸出標准錯誤流是(是FILE * 類型指針):stdin stdout stderr
- unix默認為標准I/O打開了三個文件描述符(是非負整數):STDIN_FILENO STDOUT_FILENO STDERR_FILENO 分別對應的值是0,1,2
int stdin_copy = dup(0); int stdout_copy = dup(1); close(0); close(1); int file1 = open(...); int file2 = open(...); < do your work. file1 and file2 must be 0 and 1, because open always returns lowest unused fd > close(file1); close(file2); dup2(stdin_copy, 0); dup2(stdout_copy, 1); close(stdin_copy); close(stdout_copy);
DUP(2) Linux Programmer's Manual DUP(2) NAME dup, dup2, dup3 - duplicate a file descriptor SYNOPSIS #include <unistd.h> int dup(int oldfd); int dup2(int oldfd, int newfd); #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <unistd.h> int dup3(int oldfd, int newfd, int flags); DESCRIPTION These system calls create a copy of the file descriptor oldfd. dup() uses the lowest-numbered unused descriptor for the new descriptor. dup2() makes newfd be the copy of oldfd, closing newfd first if necessary, but note the following: * If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed. * If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd. After a successful return from one of these system calls, the old and new file descriptors may be used inter‐ changeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other. The two descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off. dup3() is the same as dup2(), except that: * The caller can force the close-on-exec flag to be set for the new file descriptor by specifying O_CLOEXEC in flags. See the description of the same flag in open(2) for reasons why this may be useful. * If oldfd equals newfd, then dup3() fails with the error EINVAL. RETURN VALUE On success, these system calls return the new descriptor. On error, -1 is returned, and errno is set appropri‐ ately.
