简体   繁体   English

关闭FILE指针而不关闭基础文件描述符

[英]Close a FILE pointer without closing the underlying file descriptor

By using fdopen() , fileno() it's possible to open streams with existing file descriptors. 通过使用fdopen()fileno() ,可以使用现有的文件描述符打开流。 However the proper way to close a file, once you've opened it with a stream is to fclose() the FILE pointer. 但是,关闭文件的正确方法是,一旦用流打开文件,就是fclose() FILE指针。 How can one close the stream, but retain the open file descriptor? 如何关闭流,但保留打开的文件描述符?

This behaviour is akin to calling fflush() and then fileno() , and then never using the FILE pointer again, except in closing. 此行为类似于调用fflush()然后调用fileno() ,然后再次使用FILE指针,除非在关闭时。 An additional concern is that if you then fdopen() again, there are now multiple FILE pointers, and you can only close one of them. 另外一个问题是,如果你再次使用fdopen() ,那么现在有多个FILE指针,你只能关闭其中一个。

If you're on a POSIXy system (which I assume you are, since you have fileno() ), you can use dup() to clone the file descriptor: 如果你在POSIXy系统上(我假设你是,因为你有fileno() ),你可以使用dup()来克隆文件描述符:

int newfd = dup(fileno(stream));
fclose(stream);

Or you can hand fdopen() a duplicate file descriptor: 或者您可以将fdopen()重复的文件描述符:

FILE *stream = fdopen(dup(fd), "r");

Either way, the other copy of the fd won't close with the FILE * . 无论哪种方式,fd的另一个副本都不会以FILE * However, keep in mind the location pointer is shared, so be careful if you are using both at the same time. 但是,请记住位置指针共享的,因此如果同时使用两者,请务必小心。 Also, any fcntl() locks held on the original fd will be released when you close the copy. 此外,关闭副本时, 释放原始fd上保存的任何fcntl()锁。

如果其他一切都失败了,dup(2)可能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM