在所有编程语言(至少我使用的)中,必须先打开一个文件,然后才能对其进行读写。

但是这个开放操作实际上是做什么的呢?

典型函数的手册页面实际上没有告诉你任何东西,除了它“打开一个文件进行读写”:

http://www.cplusplus.com/reference/cstdio/fopen/

https://docs.python.org/3/library/functions.html#open

显然,通过使用该函数,您可以知道它涉及到创建某种对象,以方便访问文件。

另一种说法是,如果我要实现一个开放函数,它在Linux上需要做什么?


当前回答

在它的核心,当打开阅读时,实际上不需要发生任何花哨的事情。它所需要做的就是检查文件是否存在,并且应用程序有足够的权限来读取它,并创建一个句柄,您可以在这个句柄上向文件发出读取命令。

正是在这些命令上,实际的读取将被分派。

操作系统通常会通过开始一个读操作来填充与句柄相关的缓冲区来开始读取操作。然后,当您实际执行读取操作时,它可以立即返回缓冲区的内容,而不需要等待磁盘IO。

为了打开一个新文件写操作系统将需要在目录中添加一个新(当前为空)文件的条目。再次创建一个句柄,您可以在其上发出写入命令。

其他回答

Basically, a call to open needs to find the file, and then record whatever it needs to so that later I/O operations can find it again. That's quite vague, but it will be true on all the operating systems I can immediately think of. The specifics vary from platform to platform. Many answers already on here talk about modern-day desktop operating systems. I've done a little programming on CP/M, so I will offer my knowledge about how it works on CP/M (MS-DOS probably works in the same way, but for security reasons, it is not normally done like this today).

On CP/M you have a thing called the FCB (as you mentioned C, you could call it a struct; it really is a 35-byte contiguous area in RAM containing various fields). The FCB has fields to write the file-name and a (4-bit) integer identifying the disk drive. Then, when you call the kernel's Open File, you pass a pointer to this struct by placing it in one of the CPU's registers. Some time later, the operating system returns with the struct slightly changed. Whatever I/O you do to this file, you pass a pointer to this struct to the system call.

What does CP/M do with this FCB? It reserves certain fields for its own use, and uses these to keep track of the file, so you had better not ever touch them from inside your program. The Open File operation searches through the table at the start of the disk for a file with the same name as what's in the FCB (the '?' wildcard character matches any character). If it finds a file, it copies some information into the FCB, including the file's physical location(s) on the disk, so that subsequent I/O calls ultimately call the BIOS which may pass these locations to the disk driver. At this level, specifics vary.

在它的核心,当打开阅读时,实际上不需要发生任何花哨的事情。它所需要做的就是检查文件是否存在,并且应用程序有足够的权限来读取它,并创建一个句柄,您可以在这个句柄上向文件发出读取命令。

正是在这些命令上,实际的读取将被分派。

操作系统通常会通过开始一个读操作来填充与句柄相关的缓冲区来开始读取操作。然后,当您实际执行读取操作时,它可以立即返回缓冲区的内容,而不需要等待磁盘IO。

为了打开一个新文件写操作系统将需要在目录中添加一个新(当前为空)文件的条目。再次创建一个句柄,您可以在其上发出写入命令。

当你打开一个文件时到底会发生什么,这取决于操作系统。下面我将描述在Linux中发生的事情,因为它可以让您了解当您打开一个文件时会发生什么,如果您对更详细的内容感兴趣,您可以检查源代码。我没有涉及权限,因为这会使这个答案太长。

In Linux every file is recognised by a structure called inode. Each structure has an unique number and every file only gets one inode number. This structure stores meta data for a file, for example file-size, file-permissions, time stamps and pointer to disk blocks, however, not the actual file name itself. Each file (and directory) contains a file name entry and the inode number for lookup. When you open a file, assuming you have the relevant permissions, a file descriptor is created using the unique inode number associated with file name. As many processes/applications can point to the same file, inode has a link field that maintains the total count of links to the file. If a file is present in a directory, its link count is one, if it has a hard link its link count will be two and if a file is opened by a process, the link count will be incremented by 1.

记账,主要是。这包括各种检查,如“文件是否存在?”和“我是否有权限打开此文件进行写入?”。

但这些都是内核的东西——除非你正在实现自己的玩具操作系统,没有太多的东西需要深入研究(如果你是,玩得开心——这是一个很好的学习经历)。当然,您仍然应该了解在打开文件时可能收到的所有错误代码,以便正确地处理它们——但这些通常都是不错的小抽象。

代码级别上最重要的部分是,它为您提供了打开文件的句柄,您可以将其用于对文件进行的所有其他操作。难道不能使用文件名来代替这个任意的句柄吗?当然,但使用手柄也有一些好处:

The system can keep track of all the files that are currently open, and prevent them from being deleted (for example). Modern OSs are built around handles - there's tons of useful things you can do with handles, and all the different kinds of handles behave almost identically. For example, when an asynchronous I/O operation completes on a Windows file handle, the handle is signalled - this allows you to block on the handle until it's signalled, or to complete the operation entirely asynchronously. Waiting on a file handle is exactly the same as waiting on a thread handle (signalled e.g. when the thread ends), a process handle (again, signalled when the process ends), or a socket (when some asynchronous operation completes). Just as importantly, handles are owned by their respective processes, so when a process is terminated unexpectedly (or the application is poorly written), the OS knows what handles it can release. Most operations are positional - you read from the last position in your file. By using a handle to identify a particular "opening" of a file, you can have multiple concurrent handles to the same file, each reading from their own places. In a way, the handle acts as a moveable window into the file (and a way to issue asynchronous I/O requests, which are very handy). Handles are much smaller than file names. A handle is usually the size of a pointer, typically 4 or 8 bytes. On the other hand, filenames can have hundreds of bytes. Handles allow the OS to move the file, even though applications have it open - the handle is still valid, and it still points to the same file, even though the file name has changed.

您还可以使用其他一些技巧(例如,在进程之间共享句柄,从而在不使用物理文件的情况下拥有通信通道;在unix系统上,文件也用于设备和各种其他虚拟通道,所以这不是严格必要的),但它们并没有真正绑定到open操作本身,所以我不打算深入研究这一点。

我建议您通过open()系统调用的简化版本来了解本指南。它使用下面的代码片段,它代表了打开文件时在幕后发生的事情。

0  int sys_open(const char *filename, int flags, int mode) {
1      char *tmp = getname(filename);
2      int fd = get_unused_fd();
3      struct file *f = filp_open(tmp, flags, mode);
4      fd_install(fd, f);
5      putname(tmp);
6      return fd;
7  }

简单地说,下面是代码逐行执行的操作:

Allocate a block of kernel-controlled memory and copy the filename into it from user-controlled memory. Pick an unused file descriptor, which you can think of as an integer index into a growable list of currently open files. Each process has its own such list, though it's maintained by the kernel; your code can't access it directly. An entry in the list contains whatever information the underlying filesystem will use to pull bytes off the disk, such as inode number, process permissions, open flags, and so on. The filp_open function has the implementation struct file *filp_open(const char *filename, int flags, int mode) { struct nameidata nd; open_namei(filename, flags, mode, &nd); return dentry_open(nd.dentry, nd.mnt, flags); } which does two things: Use the filesystem to look up the inode (or more generally, whatever sort of internal identifier the filesystem uses) corresponding to the filename or path that was passed in. Create a struct file with the essential information about the inode and return it. This struct becomes the entry in that list of open files that I mentioned earlier. Store ("install") the returned struct into the process's list of open files. Free the allocated block of kernel-controlled memory. Return the file descriptor, which can then be passed to file operation functions like read(), write(), and close(). Each of these will hand off control to the kernel, which can use the file descriptor to look up the corresponding file pointer in the process's list, and use the information in that file pointer to actually perform the reading, writing, or closing.

如果您有雄心壮志,可以将这个简化的示例与Linux内核中open()系统调用的实现进行比较,这是一个名为do_sys_open()的函数。你应该不难找到相似之处。


当然,这只是调用open()时发生的事情的“顶层”——或者更准确地说,它是在打开文件的过程中调用的内核代码的最高级别部分。高级编程语言可能会在此基础上添加额外的层。有很多事情发生在较低的层次上。(感谢Ruslan和pjc50的解释。)大致从上到下:

open_namei() and dentry_open() invoke filesystem code, which is also part of the kernel, to access metadata and content for files and directories. The filesystem reads raw bytes from the disk and interprets those byte patterns as a tree of files and directories. The filesystem uses the block device layer, again part of the kernel, to obtain those raw bytes from the drive. (Fun fact: Linux lets you access raw data from the block device layer using /dev/sda and the like.) The block device layer invokes a storage device driver, which is also kernel code, to translate from a medium-level instruction like "read sector X" to individual input/output instructions in machine code. There are several types of storage device drivers, including IDE, (S)ATA, SCSI, Firewire, and so on, corresponding to the different communication standards that a drive could use. (Note that the naming is a mess.) The I/O instructions use the built-in capabilities of the processor chip and the motherboard controller to send and receive electrical signals on the wire going to the physical drive. This is hardware, not software. On the other end of the wire, the disk's firmware (embedded control code) interprets the electrical signals to spin the platters and move the heads (HDD), or read a flash ROM cell (SSD), or whatever is necessary to access data on that type of storage device.

由于缓存,这也可能有些不正确。严肃地说,我漏掉了很多细节——一个人(不是我)可以写好几本书来描述整个过程是如何工作的。但这应该能给你一个概念。