fcntl problems

Miles semanticist at gmail.com
Fri Aug 31 16:42:49 CEST 2007


On 8/31/07, mhearne808 wrote:
> I have a script that will be run from a cron job once a minute.  One
> of the things this script will do is open a file to stash some
> temporary results.  I expect that this script will always finish its
> work in less than 15 seconds, but I didn't want to depend on that.
> Thus I started to look into file locking, which I had hoped I could
> use in the following fashion:
>
> Process A opens file foo
> Process A locks file foo
> Process A takes more than a minute to do its work
> Process B wakes up
> Process B determines that file foo is locked
> Process B quits in disgust
> Process A finishes its work

That would look like (untested):

import fcntl, sys
f = open('foo', 'w+')
try:
    fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError, e:
    if e.args[0] == 35:
        sys.exit(1)
    else:
        raise
f.seek(0, 2) # seek to end
# do your thing with the file
f.flush()
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
f.close()

-Miles



More information about the Python-list mailing list