#!/usr/bin/env python

import array, fcntl, os, select, subprocess, pty, time

master_fd, slave_fd = pty.openpty()
fcntl.fcntl(master_fd, fcntl.F_SETFL,
	fcntl.fcntl(master_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
master_file = os.fdopen(master_fd, 'r')
p = select.poll()
p.register(master_fd, select.POLLIN|select.POLLHUP)
args = ["/bin/sh", "-c", "true"]
proc = subprocess.Popen(args, stdin=slave_fd,
	stderr=slave_fd, stdout=slave_fd)
os.close(slave_fd)
time.sleep(2)
stop = False
while not stop:
	for fd, events in p.poll():
		print "events:", events,
		if events & select.POLLIN:
			print "POLLIN",
		if events & select.POLLNVAL:
			print "POLLNVAL",
		if events & select.POLLHUP:
			print "POLLHUP",
		print
		if events & select.POLLIN:
			buf = array.array('B')
			try:
				buf.fromfile(master_file, 4096)
			except EOFError:
				pass
			print "read: %d bytes" % len(buf)
			if not buf:
				stop = True
				break
		if events & select.POLLHUP:
			stop = True
			break
		if events & select.POLLNVAL:
			stop = True
			break

print "wait:", proc.wait()
