chello
chello

Reputation: 155

How does an open() system call return a file descriptor?

I want to know what happens in the kernel when an open() system call is invoked? How does it return a file descriptor for a file?

Upvotes: 3

Views: 2091

Answers (3)

Halim Qarroum
Halim Qarroum

Reputation: 14103

The kernel creates internally a structure containing additional informations about the file you did just open. This structure holds informations such as the inode number, the name of the file on the file system, its size, its associated superblock, etc ...

In fact, within the kernel, it is the VFS (Virtual File System) that handles I/O operations on a file will it be local (on you hard disk) or remote (located on an FTP server for instance like ftpfs does).

Every file systems on GNU/Linux implements the same mechanisms of opening/reading/writing/closing files. This ensures every developers don't have to bother about what kind of file they are trying to access, no matter what kind of file you are interacting with, the same open(), read() ... APIs can be used. You can find additional informations on what the VFS is here and here (great article by IBM).

Finally, each file descriptor that is returned by let's say open is relative to your program, so the first file you might be opening will be associated to the file descriptor 3 and so on ... It is possible to find out what file descriptors are binded to each process on many GNU/Linux distributions via /proc/{pid_of_your_process}.

Upvotes: 3

evil otto
evil otto

Reputation: 10582

If you really want to dive deep, you can browse the source for many unix variants. For linux, check out http://lxr.linux.no/#linux+v3.9/fs/open.c -- search for SYSCALL_DEFINE3(open, to get to the actual "open" syscall.

Upvotes: 1

typ1232
typ1232

Reputation: 5607

The kernel:

  • looks for the file (hard drive, usb, named pipes, standard streams, ...)
  • if everything went well, saves itself a descriptor that you opened the file
  • returns you a descriptor
  • if you close() or the process exits, releases it's info about your open()

Upvotes: 0

Related Questions