Skip to content

Instantly share code, notes, and snippets.

@VigneshChennai
Last active August 29, 2015 14:15
Show Gist options
  • Save VigneshChennai/35bb64d41e4a4beb2225 to your computer and use it in GitHub Desktop.
Save VigneshChennai/35bb64d41e4a4beb2225 to your computer and use it in GitHub Desktop.
PyDaemonize - A python function to daemonize a python application
#!/usr/bin/env python
# PyDaemonize is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# PyDaemonize is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with PyDaemonize. If not, see <http://www.gnu.org/licenses/>.
import os
def daemonize(log_folder, wd="/", umask=0):
try:
f = os.fork()
except OSError as e:
print("SEVERE: Error forking.. <{fork}>".format(fork=e))
print("SEVERE: Trace -> {trace}".format(
trace=traceback.format_exc()))
raise e from None
if f != 0:
sys.exit(0)
else:
signal.signal(signal.SIGHUP, lambda x, y: print("SIGHUP received during process forking, ignoring signal"))
os.chdir(wd)
os.setsid()
os.umask(umask)
try:
f = os.fork()
except OSError as e:
print("SEVERE: Error forking.. <{fork}>".format(fork=e))
print("SEVERE: Trace -> {trace}".format(
trace=traceback.format_exc()))
raise e from None
if f != 0:
sys.exit(0)
print("INFO: Started as Daemon")
r = open("/dev/null", "r")
os.dup2(r.fileno(), 0)
buffering = 1 # line buffering
w = open(log_folder, "w", buffering=buffering)
os.dup2(w.fileno(), 1)
os.dup2(w.fileno(), 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment