Reputation: 165
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.
I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).
Any suggestions?
Upvotes: 4
Views: 6348
Reputation: 57774
In Unix/Solaris/Linux, you can examine /proc/
pid/fd/*
if you know the pid. You could also scan all the /proc/*/fd entries.
For Windows, I'd look into what the sysinternals.com tool ProcMon, now called Process Monitor does. I can't recall if there used to be source code available for that or not.
Upvotes: 1
Reputation: 14462
You can check it with select
and poll
. Select will return EBADF
if a 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've not tested this code but the documentation tells this.
Also that this is not exactly precise since errno can be EBADF for different reasons too.
EDIT: Another thing: If you open a file right after closing another it will most likely have the same fd as the previous, so this only works semi-decent if you want to check if all files have been closed.
Upvotes: 1
Reputation: 4282
It's not a proper unit-test if you're relying on opening \ closing files like this - such tests can randomly fail for a variety of reasons, leading to false positives and general confusion.
Instead, consider abstracting away the file operations and ensuring that close is called on your representation of the file.
Upvotes: 0
Reputation: 126203
If you want to know if a given file in a filesystem is open by some process on the machine, there's a useful tool called lsof which can tell you this for a variety of unix and unix-like systems.
Upvotes: 2
Reputation: 347216
There is no way to check if a file handle is still open or not.
If you're using C++ you can simply always use RAII and you won't have to worry about unclosed file handles.
Otherwise you can never call the system APIs and instead call your wrapper APIs. Every time you open you can add the path to a vector, everything you close you can remove that path. At the end just check if you have a zero size on your vector.
Upvotes: 1