
from __future__ import print_function

"""
RCSid:
	$Id: daemonize.py,v 1.2 2013/12/13 00:10:38 sjg Exp $

	@(#) Copyright (c) 2012 Simon J. Gerraty

	This file is provided in the hope that it will
	be of use.  There is absolutely NO WARRANTY.
	Permission to copy, redistribute or otherwise
	use this file is hereby granted provided that 
	the above copyright notice and this notice are
	left intact. 
      
	Please send copies of changes and bug-fixes to:
	sjg@crufty.net

"""

import os

def daemonize():
    """ensure we have no controlling tty"""
    try:
        t = os.ttyname(0)
    except:
        return None
    os.close(0)
    p = os.fork()
    assert p >= 0
    if p > 0:
        os._exit(0)
    os.setsid()
    return os.getpid()

if __name__ == '__main__':
    import sys, time

    p = os.getpid()
    os.system('ps axl | egrep "PID|{0}" | grep -v grep'.format(p))
    print(p, "daemonize...")
    p = daemonize()
    if p:
        print(p, "done")
        os.system('ps axl | egrep "PID|{0}" | grep -v grep'.format(p))
        time.sleep(8) 
        print(p, "bye")

    sys.exit(0)
