Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1 | import os |
| 2 | import sys |
| 3 | import string |
| 4 | |
| 5 | MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???) |
| 6 | |
| 7 | def popen2(cmd): |
Guido van Rossum | 971ee13 | 1995-08-07 20:17:23 +0000 | [diff] [blame] | 8 | cmd = ['/bin/sh', '-c', cmd] |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 9 | p2cread, p2cwrite = os.pipe() |
| 10 | c2pread, c2pwrite = os.pipe() |
| 11 | pid = os.fork() |
| 12 | if pid == 0: |
| 13 | # Child |
| 14 | os.close(0) |
| 15 | os.close(1) |
| 16 | if os.dup(p2cread) <> 0: |
| 17 | sys.stderr.write('popen2: bad read dup\n') |
| 18 | if os.dup(c2pwrite) <> 1: |
| 19 | sys.stderr.write('popen2: bad write dup\n') |
| 20 | for i in range(3, MAXFD): |
| 21 | try: |
| 22 | os.close(i) |
| 23 | except: |
| 24 | pass |
| 25 | try: |
| 26 | os.execv(cmd[0], cmd) |
| 27 | finally: |
| 28 | os._exit(1) |
| 29 | # Shouldn't come here, I guess |
| 30 | os._exit(1) |
| 31 | os.close(p2cread) |
| 32 | tochild = os.fdopen(p2cwrite, 'w') |
| 33 | os.close(c2pwrite) |
| 34 | fromchild = os.fdopen(c2pread, 'r') |
| 35 | return fromchild, tochild |