File: class/Workbook/Examples/Lecture10/ipc.py

import os

def spawn(prog, args):
    pipe1 = os.pipe()      # (parent input, child output)
    pipe2 = os.pipe()      # (child input,  parent output)
    pid = os.fork()        # make a copy of this process
    if pid:
        # in parent process
        os.close(pipe1[1])         # close child ends here
        os.close(pipe2[0])
        os.dup2(pipe1[0], 0)       # sys.stdin  = pipe1[0]
        os.dup2(pipe2[1], 1)       # sys.stdout = pipe2[1]
    else:
        # in child process
        os.close(pipe1[0])         # close parent ends here
        os.close(pipe2[1])
        os.dup2(pipe2[0], 0)       # sys.stdin  = pipe2[0]
        os.dup2(pipe1[1], 1)       # sys.stdout = pipe1[1]
        cmd = (prog,) + args
        os.execv(prog, cmd)        # overlay new program



[Home page] Books Code Blog Python Author Train Find ©M.Lutz