"""
Launch a process (given through argv) similar to how a shell would do it.
"""

import signal
import subprocess
import sys
import os


def preexec_fn():
    # Block SIGTTOU generated by the tcsetpgrp call
    orig_mask = signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGTTOU])

    # Put us in a new process group.
    os.setpgid(0, 0)

    # And put it in the foreground.
    fd = os.open("/dev/tty", os.O_RDONLY)
    os.tcsetpgrp(fd, os.getpgid(0))
    os.close(fd)

    signal.pthread_sigmask(signal.SIG_SETMASK, orig_mask)


if __name__ == "__main__":
    child = subprocess.Popen(sys.argv[1:], preexec_fn=preexec_fn)
    print("PID=%d" % child.pid)

    _, status = os.waitpid(child.pid, os.WUNTRACED)
    print("STATUS=%d" % status)

    returncode = child.wait()
    print("RETURNCODE=%d" % returncode)
