How to determine if a file has been closed

I am writing unit test and I am trying to find a way to check if my class has the file descriptor closed correctly (it uses open () and close () in the old style. Ideally, I would like to be able to do this without having access to the actual descriptor - I want to check a file in the file system and determine if it is open elsewhere.

I tried doing this through exclusive file locks, but I had no luck. In addition, file locks are very non-cross-platform (this should work on Solaris, Linux, and Windows).

Any suggestions?

+4
source share
5 answers

This is not a valid unit test if you rely on opening / closing such files - such tests can randomly fail for various reasons, which leads to false positives and general confusion.

Instead, consider abstracting the actions of the file and make sure that close is called for your view of the file.

0
source

If you want to find out if a file is open on a file system by any process on the machine, there is a useful lsof tool that can tell you about this for various Unix and Unix-like systems.

+2
source

There is no way to check if the file descriptor is all open.

If you use C ++, you can just use RAII and you don’t have to worry about unclosed files.

Otherwise, you can never call the system APIs and call the wrapper APIs instead. Each time you open, you can add a path to the vector, everything that you close can delete this path. In the end, just check if you have zero size on your vector.

+1
source

You can check it with select and poll . Select will return EBADF if the file descriptor is closed:

 fd_set rfds; struct timeval tv = { 0, 1 }; int retval; FD_ZERO(&rfds); FD_SET(fd, &rfds); retval = select(1, &rfds, NULL, NULL, &tv); if (retval == -1 && errno == EBADF) // File is closed 

NOTE that I have not tested this code, but the documentation reports this.

In addition, this is not entirely accurate, since errno can be EBADF for various reasons.

EDIT: Another thing: if you open the file immediately after closing another, it will most likely have the same fd as the previous one, so this only works halfway if you want to check if all files were closed.

+1
source

On Unix / Solaris / Linux, you can check /proc/ pid /fd/* if you know pid. You can also see all the entries in / proc / * / fd.

On Windows, I would see what the sysinternals.com ProcMon tool does, which is now called Process Monitor . I cannot remember whether the source code was available for this or not.

+1
source

All Articles