OLD | NEW |
(Empty) | |
| 1 import os, fcntl, termios |
| 2 import time |
| 3 |
| 4 def my_forkpty(): |
| 5 |
| 6 (master_fd, slave_fd) = os.openpty() |
| 7 |
| 8 if (master_fd < 0 or slave_fd < 0): |
| 9 raise ExceptionPexpect("Forkpty failed") |
| 10 |
| 11 # slave_name = ptsname(master_fd); |
| 12 |
| 13 pid = os.fork(); |
| 14 if pid == -1: |
| 15 raise ExceptionPexpect("Forkpty failed") |
| 16 elif pid == 0: # Child |
| 17 if hasattr(termios, 'TIOCNOTTY'): |
| 18 # Some platforms require an explicit detach of the |
| 19 # current controlling tty before closing stdin, stdout, stderr. |
| 20 # OpenBSD says that this is obsolete, but doesn't hurt. |
| 21 try: |
| 22 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) |
| 23 except: |
| 24 pass |
| 25 else: #if fd >= 0: |
| 26 fcntl.ioctl(fd, termios.TIOCNOTTY, 0) |
| 27 os.close(fd) |
| 28 |
| 29 # The setsid() system call will place the process into its own session |
| 30 # which has the effect of disassociating it from the controlling termina
l. |
| 31 # This is known to be true for OpenBSD. |
| 32 os.setsid() |
| 33 # except: return posix_error(); |
| 34 |
| 35 # Verify that we are disconnected from the controlling tty. |
| 36 try: |
| 37 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) |
| 38 os.close(fd) |
| 39 raise ExceptionPexpect("Forkpty failed") |
| 40 except: |
| 41 pass |
| 42 if 'TIOCSCTTY' in dir(termios): |
| 43 # Make the pseudo terminal the controlling terminal for this process |
| 44 # (the process must not currently have a controlling terminal). |
| 45 if fcntl.ioctl(slave_fd, termios.TIOCSCTTY, '') < 0: |
| 46 raise ExceptionPexpect("Forkpty failed") |
| 47 |
| 48 # # Verify that we can open to the slave pty file. */ |
| 49 # fd = os.open(slave_name, os.O_RDWR); |
| 50 # if fd < 0: |
| 51 # raise ExceptionPexpect("Forkpty failed") |
| 52 # else: |
| 53 # os.close(fd); |
| 54 |
| 55 # Verify that we now have a controlling tty. |
| 56 fd = os.open("/dev/tty", os.O_WRONLY) |
| 57 if fd < 0: |
| 58 raise ExceptionPexpect("This process could not get a controlling tty
.") |
| 59 else: |
| 60 os.close(fd) |
| 61 |
| 62 os.close(master_fd) |
| 63 os.dup2(slave_fd, 0) |
| 64 os.dup2(slave_fd, 1) |
| 65 os.dup2(slave_fd, 2) |
| 66 if slave_fd > 2: |
| 67 os.close(slave_fd) |
| 68 pid = 0 |
| 69 |
| 70 else: |
| 71 # PARENT |
| 72 os.close(slave_fd); |
| 73 |
| 74 if pid == -1: |
| 75 raise ExceptionPexpect("This process could not get a controlling tty.") |
| 76 # if (pid == 0) |
| 77 # PyOS_AfterFork(); |
| 78 |
| 79 return (pid, master_fd) |
| 80 |
| 81 pid, fd = my_forkpty () |
| 82 if pid == 0: # child |
| 83 print 'I am not a robot!' |
| 84 else: |
| 85 print '(pid, fd) = (%d, %d)' % (pid, fd) |
| 86 time.sleep(1) # Give the child a chance to print. |
| 87 print 'Robots always say:', os.read(fd,100) |
| 88 os.close(fd) |
| 89 |
OLD | NEW |