如何不在Linux中两次打开文件? [英] How not to open a file twice in linux?

查看:117
本文介绍了如何不在Linux中两次打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有fd的链接列表和一个用于在每个条目中打开此文件的字符串.我只想在尚未打开文件的情况下打开文件并将其添加到此列表中,因为我已经打开并解析了这些文件,并且不想重复执行两次.我的想法是将文件名与该列表中的每个名称进行比较,但是我的程序会多次执行此操作,而Linux中的一个文件可以具有多个名称(软/硬链接).我认为它不应该那么复杂,因为它易于操作系统检查,是否已经使用了索引节点,r? 我已经尝试使用open和不使用flock的同一个文件,但是我总是得到一个新的fd.

I have a linked list with an fd and a string I used to open this file in each entry. I want to open and add files to this list only if this file is not already opened, because I open and parse this files and do not want to do it twice. My idea was to compare the filename with every single name in this list, but my program do it multiple times and one file in Linux can have multiple names (soft/hard links). I think it should not be so complicated, because its easy for the OS to check, whether I already used a inode or not, r? I already tried to open the same file with and without flock, but I always get a new fd.

推荐答案

成功打开文件时,请使用 fstat 在文件上.检查 struct stat st_ino和st_dev fstat提交的>已记录在您的链接列表中.如果是这样,则关闭文件描述符,然后继续下一个文件.否则,将文件描述符,文件名以及st_inost_dev值添加到列表中.

When you successfully open a file use fstat on the file. Check to see if the st_ino and st_dev of the struct stat filed in by fstat have already been recorded in your linked list. If so then close the file descriptor and move on to the next file. Otherwise add the file descriptor, the file name and st_ino and st_dev values to the list.

您可以改用 stat 在打开文件之前进行检查,但是如果通常情况下尚未打开文件,则在之后使用fstat会稍快一些.

You can instead use stat to check before opening the file, but using fstat after will be slightly faster if the usual case is that file hasn't already been opened.

这篇关于如何不在Linux中两次打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆