自动创建pid文件,并加锁



点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import sys
  4. import os
  5. import re
  6. import traceback
  7. import fcntl

  8. class PidFile():
  9.     def __init__(self, file = None):
  10.         if file == None:
  11.             argv0_list = sys.argv[0].split("\\")
  12.             scname = argv0_list[len(argv0_list) - 1]
  13.             if re.search(".py$", scname):
  14.             scname = scname[0:-3]
  15.             self.file = "/tmp/%s.pid" % (scname)
  16.         else:
  17.             self.file = file
  18.         self.pidfile = None

  19.     def _create(self, file):
  20.         f = open(file, "w")
  21.         pid = os.getpid()
  22.         f.write("%s" % (pid))
  23.         f.close()

  24.     def __enter__(self):
  25.         if not os.path.isfile(self.file):
  26.             self._create(self.file)
  27.         self.pidfile = open(self.file, 'a+')
  28.         try:
  29.             fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
  30.             return True
  31.         except:
  32.             traceback.print_exc()
  33.             fpid = open(self.file, "r").read()
  34.             raise SystemExit("Process id %s Already running , pid to %s " % (fpid, self.file))
  35.         return False    

  36.     def __exit__(self, *args):
  37.         try:
  38.             self.pidfile.close()
  39.         except :
  40.             pass
  41.         os.remove(self.file)


  42. if __name__ == "__main__":
  43.     # use
  44.     with PidFile() as t:
  45.         print "lock file %s" % (file)
  46.         time.sleep(10)
  47.     exit(0)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26250550/viewspace-1816377/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26250550/viewspace-1816377/

你可能感兴趣的:(自动创建pid文件,并加锁)