import multiprocessing
import signal


def create_server_subprocess(target, args, logger):
    """
    Create the subprocess, set it as a daemon, setup a signal handler
    in case the parent process is killed, the child process should also be killed, then return
    the subprocess.

    :param target: Target function to run in a subprocess
    :param args: Args to pass to the function
    :return: `multiprocessing.Process`
    """
    server = multiprocessing.Process(target=target, args=args)
    server.daemon = True
    server.start()

    logger.info("Created subprocess w/ PID %s", server.pid)

    def sighandler(signum, frame):
        print("Caught SIGTERM, closing subprocess")
        server.terminate()
        exit(0)

    signal.signal(signal.SIGTERM, sighandler)
    return server