test if a file is locked?

F

Fortepianissimo

I can lock a file using the following snippet:

---
import fcntl

f=open('flock.txt','w')
fcntl.lockf(f.fileno(),fcntl.LOCK_EX)
---

If some other script tries to open 'flock.txt', it'll wait until the
file is unlocked/closed.

My question is, I'd like to tell a script to quit *immediately* if it
cannot open the file, or, if it knows the file is locked.

The reason I need this is I want to serialize parallel processes using
a lock file. Any suggestion is welcome!
 
C

Carl Banks

Fortepianissimo said:
I can lock a file using the following snippet:

---
import fcntl

f=open('flock.txt','w')
fcntl.lockf(f.fileno(),fcntl.LOCK_EX)
---

If some other script tries to open 'flock.txt', it'll wait until the
file is unlocked/closed.

My question is, I'd like to tell a script to quit *immediately* if it
cannot open the file, or, if it knows the file is locked.

The reason I need this is I want to serialize parallel processes using
a lock file. Any suggestion is welcome!


Try this:

fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
 
B

Benjamin Han

Try this:

fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)

Ok looks like I'm still missing something: so how do you get 'f' without
using open() or file()? Either of these will put the script on hold...

Thanks!
 
B

Benjamin Han

Ok looks like I'm still missing something: so how do you get 'f' without
using open() or file()? Either of these will put the script on hold...

I got it, thanks!
 
C

Carl Banks

Benjamin said:
Ok looks like I'm still missing something: so how do you get 'f' without
using open() or file()? Either of these will put the script on hold...

Thanks!

Have you tried it? (Hint: it's not "open" that waits until the file
is unlocked.)
 
G

Guest

I can lock a file using the following snippet:
---
import fcntl

f=open('flock.txt','w')
fcntl.lockf(f.fileno(),fcntl.LOCK_EX)

This is not true on my system (Linux-2.4.23/glibc-2.3.2), after locking the
file Ican still open it with another script or program (like "cat").

The other script blocks only when I try to lock the file again.
My question is, I'd like to tell a script to quit *immediately* if it
cannot open the file, or, if it knows the file is locked.

try this:
fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
it will throw an exception if the file is locked:
IOError: [Errno 11] Resource temporarily unavailable
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top