Skip to content

Instantly share code, notes, and snippets.

@powdahound
Created September 29, 2010 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save powdahound/603154 to your computer and use it in GitHub Desktop.
Save powdahound/603154 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import os
def daemonize():
# See http://www.faqs.org/faqs/unix-faq/programmer/faq/ - Section 1.7
print('--- %s: daemonizing' % os.getpid())
if os.fork(): # launch child and...
print('--- %s: kill parent 1' % os.getpid())
os._exit(0) # kill off parent
print('--- %s: old sid: %r' % (os.getpid(), os.getsid(os.getpid())))
os.setsid()
print('--- %s: new sid: %r' % (os.getpid(), os.getsid(os.getpid())))
if os.fork(): # launch child and...
print('--- %s: kill parent 2' % os.getpid())
os._exit(0) # kill off parent again.
# File descriptor redirection intentionally left out so that we continue to see logging on stdout.
# The failure case doesn't make it here anyway.
print('--- %s: daemonizing done' % os.getpid())
if __name__ == "__main__":
print 'starting as %d' % os.getpid()
daemonize()
print 'stopping as %s' % os.getpid()
On Ubuntu 10.04 (Python 2.6.5) - the error case:
imac:~ ssh -t lucidbox "./fork.py"
starting as 22325
--- 22325: daemonizing
--- 22325: kill parent 1
Connection to lucidbox closed.
On Ubuntu 9.04 (Python 2.6.2):
imac:~ ssh -t jauntybox "./fork.py"
starting as 23203
--- 23203: daemonizing
--- 23227: old sid: 23203
--- 23227: new sid: 23227
--- 23228: daemonizing done
stopping as 23228
--- 23227: kill parent 2
--- 23203: kill parent 1
Connection to jauntybox closed.
Either machine without using pseudo terminal:
imac:~ ssh box "./fork.py"
starting as 22629
--- 22629: daemonizing
--- 22654: old sid: 22629
--- 22654: new sid: 22654
--- 22655: daemonizing done
stopping as 22655
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment