同一文件的多个文件描述符,C
我有一个多线程应用程序正在打开和读取同一文件(而不是写入)。我为每个线程打开不同的文件描述符(但它们都指向同一个文件)。然后,每个线程读取该文件,并可能关闭它,如果到达 EOF,则再次打开它。这样可以吗?如果我对文件描述符执行 fclose() 是否会影响指向同一文件的其他文件描述符?
I have a multithreaded application that is opening and reading the same file (not writing). I am opening a different file descriptor for each thread (but they all point to the same file). Each thread then reads the file and may close it and open it again if EOF is reached. Is this ok? If I perform fclose() on a file descriptor does it affect the other file descritptors that point to the same file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 Linux 系统,您不需要多个文件描述符来执行此操作。您可以共享单个文件描述符并使用 pread 原子地执行查找/读取操作,而无需根本修改文件描述符。
For Linux systems you don't need multiple file descriptors to do this. You can share a single file descriptor and use pread to atomically do a seek / read operation without modifying the file descriptor at all.
没关系。您可以随时打开同一个文件,并且每个文件描述符将彼此独立。
That's ok. You can open all times you want the same file and each file descriptor will be independent from each other.
如果每个线程都有自己的文件句柄,那应该可以正常工作。由于您提到使用
fclose()
,这表明您还在每个线程中使用fopen()
,并且每个线程仅影响其自己的FILE *
> 变量。有问题吗?
That should work fine, provided each thread has its own file handle. Since you mention use of
fclose()
, that suggests you are also usingfopen()
in each thread and each thread only affects its ownFILE *
variable.Is there a problem?