linux下关闭标准输出,然后重新打开
通过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.