#!/usr/bin/env python import sys import os import fcntl def set_cloexec_flag(fd): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) def run(args): c2pread, c2pwrite = os.pipe() errpipe_read, errpipe_write = os.pipe() set_cloexec_flag(errpipe_write) pid = os.fork() if pid == 0: # Child try: os.close(c2pread) os.close(errpipe_read) os.dup2(c2pwrite, 1) os.dup2(c2pwrite, 2) os.close(c2pwrite) os.execvp(args[0], args) except: os.write(errpipe_write, "1") os._exit(255) # Parent os.close(errpipe_write) os.close(c2pwrite) data = os.read(errpipe_read, 1048576) os.close(errpipe_read) if data != "": print >>sys.stderr, "EXCEPTION IN CHILD" sys.exit(1) selfstdout = os.fdopen(c2pread, 'rb', 0) print "DATA:", repr(selfstdout.read()) print "DATA:", repr(selfstdout.read()) args = [sys.executable, "-c", 'import sys;' \ 'sys.stdout.write("apple");' \ 'sys.stdout.flush();' \ 'sys.stderr.write("orange")'] run(args)