Usually we don’t do the such a check that way - it is racy. Consider
Now imagine 2 programmes doing that same check, running at once. Maybe
their execution looks like this:
Observe that both decide that the file is not in use (because it isn’t
when they do the check), then both go ahead and use the file, exactly
what you wanted to avoid. This kind of situation is called a race.
Instead, the usual approach is a lock of some kind, enforcing mutual
exclusion. What’s available depends on the platform. The pattern looks
The lock is such that you can’t obtain it if someone else has the lock.
The “lock-the-file” step might come in 2 flavours: blocking - you always
get the lock, but not until it is released, or nonblocking - you may
fail to get the lock, in which case you should try again later.
On UNIX platforms the fcntl module has lockf and flock methods - the
pattern is that you open the file nondestructively, then take the lock
before doing any work.
In Windows you often can’t open a file already in use. I don’t know what
the accepted method is there.
Cameron Simpson email@example.com