-1

I found this question but I do not know how to use the suggestion. I have tried

with open(fullname) as filein:
    fcntl.lockf(filein, fcntl.LOCK_EX | fcntl.LOCK_NB)

and

with open(fullname) as filein:
    fcntl.lockf(filein.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

but in both cases I get an error

OSError: [Errno 9] Bad file descriptor

I want to use this method to check if a file is "locked", and ideally to unlock it.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Alex
  • 41,580
  • 88
  • 260
  • 469
  • "I want to use this method to check if a file is "locked", and ideally to unlock it." - this sounds like you're going down the wrong path to solve an underlying goal. `fcntl.lockf` will not allow you to read, write, open, move, or delete any file that you wouldn't already be able to read, write, open, move, or delete. – user2357112 Apr 07 '23 at 09:19
  • At least I could identify all files that are locked and unlock them manually (so I can finally empty the Bin of an external hard disk using MacOS...) – Alex Apr 07 '23 at 09:20
  • File locks are not what you think they are. They don't actually prevent you from doing anything to a file, and they are not what is stopping you from emptying your recycle bin. – user2357112 Apr 07 '23 at 09:22
  • It is blocking me from deleting files. See this question for more context: https://apple.stackexchange.com/questions/458231/how-to-remove-files-in-trash-on-external-disk-with-a-mac-when-operation-cant-b#458231 – Alex Apr 07 '23 at 09:23
  • That is a completely unrelated thing, despite the confusingly similar name. `fcntl.lockf` has nothing to do with that. – user2357112 Apr 07 '23 at 09:24
  • So there are two different meaning related to "a file is locked"? Can you explain more or have a link to documentation? – Alex Apr 07 '23 at 09:25
  • 2
    `fcntl.lockf` is a wrapper around [fcntl advisory locking](https://pubs.opengroup.org/onlinepubs/007904975/functions/fcntl.html), a mechanism for cooperating processes to coordinate access to a file or sections of a file. It lets individual processes say "I'm using this file" or "I'm using the part of this file from [here] to [here]", but the only effect is to prevent other processes from acquiring conflicting locks - it does nothing else. It's completely unrelated to the mac OS "locked" file property. – user2357112 Apr 07 '23 at 09:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/253022/discussion-between-alex-and-user2357112). – Alex Apr 07 '23 at 09:44

1 Answers1

-3

Try to apply the next code snippet:

import fcntl

with open(fullname, 'r') as filein:
    try:
        fcntl.flock(filein, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print(f"File {fullname} is locked.")
    else:
        print(f"File {fullname} is locked, but...") 
        fcntl.flock(filein, fcntl.LOCK_UN)
        print("now is not.")
Aksen P
  • 4,564
  • 3
  • 14
  • 27