Home > Python > Application lock file implementation

Application lock file implementation

Its always a good practice to put a check in the code to see if another instance of the same app is running.

This is helpful in case you have a cron job that is called every hour and single execution of an app can take more then a hour, in this case if we dont have a check in place then that means we can have more then one instance of the same at one time.

Recently I had to add the same kind of check for one of my Python scripts, sharing that if it might help someone trying to do the same:

if os.access(os.path.expanduser("~/.application.lock"), os.F_OK):
       lck_fl = open(os.path.expanduser("~/.application.lock"), "r")
       lck_fl.seek(0)
       oldpid = lck_fl.readline()
       if os.path.exists("/proc/%s" % oldpid):
           print "lck_fl exist! process is already running"
           print "Process is already running as pid %s," % oldpid
           sys.exit(1)
       else:
           print "lck_fl exists but no PID found as current process"
           print "Removing lck_fl of application process: %s" % oldpid
           os.remove(os.path.expanduser("~/.application.lock"))
lck_fl = open(os.path.expanduser("~/.application.lock"), "w")
lck_fl.write("%s" % os.getpid())
lck_fl.close

Shoaib Mir
shoaibmir[@]gmail.com

Advertisements
Categories: Python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: