1

I would like to make a simple locking mechanism in Python without having to rely on the existing libraries for locking (namely fcntl and probably others)

I already have a small stub, but after searching for a bit I couldn't find a good on answer on how to manually create the lock file and put the process PID inside. Here is my stub:

dir_name = "/var/lock/mycompany"
file_name = "myapp.pid"
lock = os.path.join(dir_name, file_name)

if os.path.exists(lock):
    print >> sys.stderr, "already running under %s, exiting..." % lock
    # display process PID contained in the file, not relevant to my question
    sys.exit(ERROR_LOCK)
else:
    # create the file 'lock' and put the process PID inside

How can I get the current process PID and put it inside the lock file? I thought about looking at /proc filesystem but that seems a bit too much for such a simple task.

Thanks.

3
  • 3
    open(lock, 'w').write(os.getpid()) Commented Apr 18, 2012 at 19:21
  • Perfect answer thanks, guess I don't need to bother with /proc after all... Commented Apr 18, 2012 at 19:24
  • 2
    just for your info- if you ever need to interrogate a process in proc, you can do it with /proc/self. /proc/self is always a symlink to the calling process. However, for just gleaning the PID, it is overkill. Commented Apr 18, 2012 at 19:28

3 Answers 3

2

http://docs.python.org/library/os.html#os.getpid

Sign up to request clarification or add additional context in comments.

Comments

1

open(lock, 'w').write(os.getpid())

Comments

0

Don't neglect to convert the result of os.getpid() to a string with str(os.getpid()). write wants a string argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.