| 1 | |
|---|
| 2 | import os, select |
|---|
| 3 | |
|---|
| 4 | def main(): |
|---|
| 5 | # Create stdin, stdout, stderr for the child process |
|---|
| 6 | stdin = os.pipe() |
|---|
| 7 | stdout = os.pipe() |
|---|
| 8 | stderr = os.pipe() |
|---|
| 9 | |
|---|
| 10 | # Create the child |
|---|
| 11 | pid = os.fork() |
|---|
| 12 | if pid == 0: |
|---|
| 13 | child(stdin, stdout, stderr) |
|---|
| 14 | else: |
|---|
| 15 | parent(pid, stdin, stdout, stderr) |
|---|
| 16 | |
|---|
| 17 | |
|---|
| 18 | def child(stdin, stdout, stderr): |
|---|
| 19 | # close the parent sides |
|---|
| 20 | stdin, close = stdin |
|---|
| 21 | os.close(close) |
|---|
| 22 | close, stdout = stdout |
|---|
| 23 | os.close(close) |
|---|
| 24 | close, stderr = stderr |
|---|
| 25 | os.close(close) |
|---|
| 26 | |
|---|
| 27 | # wait for instructions from the parent |
|---|
| 28 | while True: |
|---|
| 29 | command = os.read(stdin, 2).strip() |
|---|
| 30 | if not command: |
|---|
| 31 | break |
|---|
| 32 | os.close(int(command)) |
|---|
| 33 | |
|---|
| 34 | |
|---|
| 35 | def parent(pid, stdin, stdout, stderr): |
|---|
| 36 | # close the child sides |
|---|
| 37 | childStdin, stdin = stdin |
|---|
| 38 | os.close(childStdin) |
|---|
| 39 | stdout, childStdout = stdout |
|---|
| 40 | os.close(childStdout) |
|---|
| 41 | stderr, childStderr = stderr |
|---|
| 42 | os.close(childStderr) |
|---|
| 43 | |
|---|
| 44 | # tell the child to close stderr |
|---|
| 45 | os.write(stdin, '%d\n' % (childStderr,)) |
|---|
| 46 | # wait for it to close |
|---|
| 47 | select.select([stderr], [], []) |
|---|
| 48 | |
|---|
| 49 | # now tell it to close the stdout |
|---|
| 50 | os.write(stdin, '%d\n' % (childStdout,)) |
|---|
| 51 | # wait for it to close |
|---|
| 52 | select.select([stdout], [], []) |
|---|
| 53 | |
|---|
| 54 | # now tell it to exit |
|---|
| 55 | os.write(stdin, '\n') |
|---|
| 56 | # and wait for it to do so |
|---|
| 57 | print os.wait() |
|---|
| 58 | |
|---|
| 59 | |
|---|
| 60 | if __name__ == '__main__': |
|---|
| 61 | main() |
|---|