Ticket #3529: demo.2.py

File demo.2.py, 1.5 KB (added by exarkun, 5 years ago)

second attempt to reproduce the problem

Line 
1
2import os, select
3
4def 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
18def 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    # Make them look like stdio and get rid of the originals
28    os.dup2(stdin, 0)
29    os.close(stdin)
30    os.dup2(stdout, 1)
31    os.close(stdout)
32    os.dup2(stderr, 2)
33    os.close(stderr)
34   
35    # wait for instructions from the parent
36    while True:
37        command = os.read(0, 2).strip()
38        if not command:
39            break
40        os.close(int(command))
41
42
43def parent(pid, stdin, stdout, stderr):
44    # close the child sides
45    close, stdin = stdin
46    os.close(close)
47    stdout, close = stdout
48    os.close(close)
49    stderr, close = stderr
50    os.close(close)
51
52    # tell the child to close stderr
53    os.write(stdin, '2\n')
54    # wait for it to close
55    select.select([stderr], [], [])
56
57    # now tell it to close the stdout
58    os.write(stdin, '1\n')
59    # wait for it to close
60    select.select([stdout], [], [])
61
62    # now tell it to exit
63    os.write(stdin, '\n')
64    # and wait for it to do so
65    print os.wait()
66
67
68if __name__ == '__main__':
69    main()