Prevent file descriptor reuse

Is there anything at all in Linux (or, in general, in POSIX OS) to ensure that no file descriptors will be reused during program execution, even if the file is closed and the other is open? I understand that this situation usually causes the file descriptor for the closed file to be reassigned to the newly opened file.

I am working on an I / O trace project, and it will make life easier if I can assume that after calling open () / fopen (), all subsequent I / O operations with this file descriptor refer to the same file.

I will take either compilation time or runtime.

If this is not possible, I can make my own accounting when I process the trace file (marking the location of all open and closed calls), but I would prefer to deflate the problem while the trace program is running.

+5
source share
3 answers

Please note that POSIX requires :

The open () function returns the file descriptor for the specified file; this is the lowest file descriptor that is not currently open for this process.

So, in the strict sense, your request will change the environment of the program, which will no longer meet the requirements of POSIX.

However, I find it best to use the LD_PRELOAD trick to intercept calls on closeand ignore them.

+7
source

SO, close(2), /dev/null FD, $LD_PRELOAD, .

+1

ptrace .

FD "" dup2(X, Y); close(X); Y , .

dup2 FD , , , - .

, , FD, .

+1
source

All Articles