Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two file descriptors to same file

Using the posix read() write() linux calls, is it guaranteed that if I write through one file descriptor and read through another file descriptor, in a serial fashion such that the two actions are mutually exclusive of each other... that my read file descriptor will always see what was written last by the write file descriptor?

i believe this is the case, but I want to make sure and the man page isn't very helpful on this

like image 978
Michael Xu Avatar asked Mar 12 '11 17:03

Michael Xu


People also ask

Can two file descriptors point to the same file?

One process can have multiple file descriptors point to the same entry (e.g., as a result of a call to dup() ) Multiple processes (e.g., a parent and child) can have file descriptors that point to the same entry.

Do Threads share the same file descriptors?

Threads in the same process share an address space and file descriptor table, so we do not need to save the page-table root pointer or the fd table.

Can file descriptor be reused?

Unlike process IDs, which are recycle only gradually, the kernel always allocates the lowest unused file descriptor when a new descriptor is created. This means that in a multi-threaded program which constantly opens and closes file descriptors, descriptors are reused very quickly.

How many file descriptors can I open?

Linux systems limit the number of file descriptors that any one process may open to 1024 per process. (This condition is not a problem on Solaris machines, x86, x64, or SPARC). After the directory server has exceeded the file descriptor limit of 1024 per process, any new process and worker threads will be blocked.


1 Answers

It depends on where you got the two file descriptors. If they come from a dup(2) call, then they share file offset and status, so doing a write(2) on one will affect the position on the other. If, on the other hand, they come from two separate open(2) calls, each will have their own file offset and status.

A file descriptor is mostly just a reference to a kernel file structure, and it is that kernel structure that contains most of the state. When you open(2) a file, you get a new kernel file structure and a new file descriptor that refers to it. When you dup(2) a file descriptor (or pass a file descriptor through sendmsg), you get a new reference to the same kernel file struct.

like image 117
Chris Dodd Avatar answered Sep 25 '22 07:09

Chris Dodd