def daemonize():
"""
This function will daemonize the script and continue executing it only
when the current session will have ended.
The rationale behind this is to clean logs after the caller has disconnected from
the machine in order to catch SSH logout records (for instance).
:return:
"""
def fork():
try:
pid = os.fork()
if pid > 0:
# Exit parent
sys.exit(0)
except OSError:
_, e = sys.exc_info()[:2]
print "Error while forking! (%s)" % e.message
sys.exit(1)
# Double fork to daemonize
fork()
os.chdir('/')
os.setsid()
os.umask(0)
fork()
print success("The script has daemonized successfully. Logs will be cleaned when this "
"session ends.")
# Dirty trick to figure out when the user has disconnected from the current session:
# try to use the file descriptor for stdout and detect when it is closed.
while True:
time.sleep(10)
try:
os.ttyname(1)
except: # Exception caught: stdout doesn't exist anymore.
return # This means the session has ended and we can proceed.
# -----------------------------------------------------------------------------
评论列表
文章目录