code_junkie

What would be the simplest way to daemonize a python script in Linux?

Nov 11th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. from os import fork, setsid, umask, dup2
  2. from sys import stdin, stdout, stderr
  3.  
  4. if fork(): exit(0)
  5. umask(0)
  6. setsid()
  7. if fork(): exit(0)
  8.  
  9. stdout.flush()
  10. stderr.flush()
  11. si = file('/dev/null', 'r')
  12. so = file('/dev/null', 'a+')
  13. se = file('/dev/null', 'a+', 0)
  14. dup2(si.fileno(), stdin.fileno())
  15. dup2(so.fileno(), stdout.fileno())
  16. dup2(se.fileno(), stderr.fileno())
  17.  
  18. from os import getpid
  19. outfile = open(pid_file, 'w')
  20. outfile.write('%i' % getpid())
  21. outfile.close()
  22.  
  23. from os import setuid, setgid, chdir
  24. from pwd import getpwnam
  25. from grp import getgrnam
  26. setuid(getpwnam('someuser').pw_uid)
  27. setgid(getgrnam('somegroup').gr_gid)
  28. chdir('/')
  29.  
  30. $ easy_install turkmenbashi
  31. import Turkmenbashi
  32.  
  33. class DebugDaemon (Turkmenbashi.Daemon):
  34.  
  35. def config(self):
  36. self.debugging = True
  37.  
  38. def go(self):
  39. self.debug('a debug message')
  40. self.info('an info message')
  41. self.warn('a warning message')
  42. self.error('an error message')
  43. self.critical('a critical message')
  44.  
  45. if __name__=="__main__":
  46. d = DebugDaemon()
  47. d.config()
  48. d.setenv(30, '/var/run/daemon.pid', '/tmp', None)
  49. d.start(d.go)
  50.  
  51. $ easy_install grizzled
  52.  
  53. >>> from grizzled.os import daemonize
  54. >>> daemon.daemonize()
Add Comment
Please, Sign In to add comment