#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3


daemonized = False

def is_daemonized():
	global daemonized
	return	daemonized

def	daemonize(print_pid=False, logfile=None):
	from os import fork, setsid, umask, dup2, getpid
	from sys import stdin, stdout, stderr
	if fork(): exit(0)
	umask(0)
	setsid()
	if fork(): exit(0)

	if print_pid:
		print("%s" % getpid())

	stdout.flush()
	stderr.flush()
	si = file('/dev/null', 'r')
	if not logfile:
		logfile = '/dev/null'
	lf = file(logfile, 'a+', 0)
	#print("stdout will go to %s:%s and stderr to %s:%s" % (logfile, so, logfile, se))
	dup2(si.fileno(), stdin.fileno())
	dup2(lf.fileno(), stdout.fileno())
	dup2(lf.fileno(), stderr.fileno())
	global daemonized
	daemonized = True
	#restore SIGCLD behaviour so waitpid() can still work?
	#signal.signal(signal.SIGCLD, signal.SIG_DFL)
