When this function is called, the process is daemonized (by forking + killing its parent).
    It becomes a background task.
    It is useful to release the console.

def daemonize(umask=0, work_dir="/", max_fd=1024, redirect="/dev/null"):
    """
    When this function is called, the process is daemonized (by forking + killing its parent).
    It becomes a background task.
    It is useful to release the console.
    """
    if not redirect:
        redirect = "/dev/null"

    if hasattr(os, "devnull"):
        redirect = os.devnull

    try:
        pid = os.fork()
    except OSError as e:
        raise Exception("%s [%d]" % (e.strerror, e.errno))

    # first child
    if pid == 0:
        os.setsid()

        try:
            # Fork a second child.
            pid = os.fork()
        except OSError as e:
            raise Exception("%s [%d]" % (e.strerror, e.errno))

        # The second child.
        if pid == 0:
            os.chdir(work_dir)
            os.umask(umask)
        else:
            # exit first child
            os._exit(0)
    else:
        # Exit parent
        os._exit(0)

    #killing inherited file descriptors
    import resource
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if maxfd == resource.RLIM_INFINITY:
        maxfd = max_fd

    # close all file descriptors.
    for fd in range(0, maxfd):
        try:
            os.close(fd)
        except OSError:
            # ignored
            pass

    os.open(redirect, os.O_RDWR) # standard input

    # Duplicate standard
    os.dup2(0, 1)			# standard output (1)
    os.dup2(0, 2)			# standard error (2)

    return os.getpid()