views:

817

answers:

4

Hi, I'd like to be able to lock directory access under windows. The following code work greatly with file or directory under POSIX system:

def flock(fd, blocking=False, exclusive=False):

    if exclusive:
        flags = fcntl.LOCK_EX
    else:
        flags = fcntl.LOCK_SH
    if not blocking:
        flags |= fcntl.LOCK_NB
    fcntl.flock(fd, flags)

But I only find a way to perform lock access for file, not directory with the following code:

def flock(fd, blocking=False, exclusive=False):

    if blocking:
        flags = msvcrt.LK_NBLCK
    else:
        flags = msvcrt.LK_LOCK
    msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name))

Have you got any idea how to improve this code and be able to lock directory access ?

Bertrand

A: 

You probably can do something like this to indirectly lock a directory with the latter flock function.

for file in os.listdir(dir):
 f = open(file)
 flock(f)

This is a limited version, since the user will be able to create new files in the directory.

kylebrooks
A: 

Yep you are right, at least I can try to lock every file of the directory but it can be painful because I need to walk into all the subdirectories of my directory. In POSIX system it's easy because directories are seen like files so, no problem with that. But in Windows when I try to open a directory, it doesn't really like that.

open(dirname)

raises exception:

OSError: [Errno 13] Permission denied: dirname

I am not really sure my solution is actually the good way to do it.

Bertrand
+1  A: 

I don't believe it's possible to use flock() on directories in windows. PHPs docs on flock() indicate that it won't even work on FAT32 filesystems.

On the other hand, Windows already tends to not allow you to delete files/directories if any files are still open. This, plus maybe using ACLs intelligently, might get you a 95% equivalent solution.

HUAGHAGUAH
A: 

I don't really know Windows. I will have a look to ACLs to find a way to use them. Thanks for your help.

Bertrand