Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing reuse of file descriptors

Tags:

c

linux

io

posix

Is there anyway in Linux (or more generally in a POSIX OS) to guarantee that during the execution of a program, no file descriptors will be reused, even if a file is closed and another opened? My understanding is that this situation would usually lead to the file descriptor for the closed file being reassigned to the newly opened file.

I'm working on an I/O tracing project and it would make life simpler if I could assume that after an open()/fopen() call, all subsequent I/O to that file descriptor is to the same file.

I'll take either a compile-time or run-time solution.

If it is not possible, I could do my own accounting when I process the trace file (noting the location of all open and close calls), but I'd prefer to squash the problem during execution of the traced program.

like image 632
mhowison Avatar asked May 20 '12 00:05

mhowison


3 Answers

Note that POSIX requires:

The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process.

So in the strictest sense, your request will change the program's environment to be no longer POSIX compliant.

That said, I think your best bet is to use the LD_PRELOAD trick to intercept calls to close and ignore them.

like image 180
Nemo Avatar answered Nov 20 '22 19:11

Nemo


You'd have to write a SO that contains a close(2) that opens /dev/null on old FDs, and then use $LD_PRELOAD to load it into process space before starting the application.

like image 20
Ignacio Vazquez-Abrams Avatar answered Nov 20 '22 20:11

Ignacio Vazquez-Abrams


You must already be ptraceing the application to intercept its file opening and closing operations.

It would appear trivial to prevent FD re-use by "injecting" dup2(X, Y); close(X); calls into the application, and adjusting Y to be anything you want.

However, the application itself could be using dup2 to force a re-use of previously closed FD, and may not work if you prevent that, so I think you'll just have to deal with this in post-processing step.

Also, it's quite easy to write an app that will run out of FDs if you disallow re-use.

like image 1
Employed Russian Avatar answered Nov 20 '22 18:11

Employed Russian