How to make subprocess run for 60 sec
Question: I have the following python script that runs. I want is to run the subprocess
to run for 60 sec and then send the SIGINT signal to subprocess and write the
output in file.If i use sleep the subprocess doesn't run.

    
    
    #!/usr/bin/python
    import os
    import subprocess
    PIPE = subprocess.PIPE
    import signal
    import time
    
    def handler(signum, frame):
        pass
    
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(60)
    command = "strace -c ./server"
    os.chdir("/root/Desktop/")
    p = subprocess.Popen(command, stdout=PIPE, stderr=PIPE)
    time.sleep(60)
    p.send_signal(signal.SIGINT)
    signal.alarm(0)
    print p.communicate()[1]
    


Answer: In Python 3.3 and newer, there is a simpler version of the answer (untested
code):

    
    
    with open('output', 'wb', 0) as output_file:
        p = subprocess.Popen("strace -c ./server".split(),
                             stdout=output_file, stderr=subprocess.STDOUT, 
                             cwd="/root/Desktop/",
                             close_fds=True)
        try:
            p.wait(60) # Wait for the child process to finish, or for 60 seconds, which ever comes first.
        except subprocess.TimeoutExpired:
            p.send_signal(signal.SIGINT)
            p.wait() # Wait fro the process to actually exit after receiving the terminate signal.
    

See also:
<https://docs.python.org/3/library/subprocess.html#subprocess.Popen.wait>

