dup2的笔记
当前项目中有段代码是为了做文件切换写入,一直没弄懂为什么打开新的文件描述符后,之前的文件描述符不需要关闭:
int fd = open(filename, O_RDWR | O_CREAT | O_APPEND | O_LARGEFILE, LOG_FILE_MODE);
dup2(fd, _fd);
dup2(fd, 1);
close(fd);
然后特地查了下dup2函数的作用,原来在dup2执行的时候,_fd所指向的文件描述符就已经关闭了:
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 interchangeably. 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.
浙公网安备 33010602011771号