code_junkie

Ensuring a single instance of an application in Linux

Nov 11th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.53 KB | None | 0 0
  1. import fcntl
  2. pid_file = 'program.pid'
  3. fp = open(pid_file, 'w')
  4. try:
  5. fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
  6. except IOError:
  7. # another instance is running
  8. sys.exit(0)
  9.  
  10. name = "MyApp-%s" % wx.GetUserId()
  11. checker = wx.SingleInstanceChecker(name)
  12. if checker.IsAnotherRunning():
  13. return False
  14.  
  15. linux# pidof myapp
  16. 8947
  17. linux# pidof nonexistent_app
  18.  
  19. linux#
  20.  
  21. import os
  22. os.getpid()
  23.  
  24. cmd = "ps -p %s -o comm=" % var_run_pid
  25. app_name = os.popen(cmd).read().strip()
  26. if len(app_name) > 0:
  27. Already running
Add Comment
Please, Sign In to add comment