Clueless: piping between 2 non-python processes
Andrew Bennetts
andrew-pythonlist at puzzling.org
Sat Oct 25 22:23:01 EDT 2003
On Sat, Oct 25, 2003 at 08:16:33PM +0200, Michael Lehmeier wrote:
>
> So I wanted to start A and B as fork, but all solutions to create a pipe
> between them seem to demand that at least one of the two processes is in
> python itself.
> Or maybe I just understood it wrong.
>
> So the basic problem is:
> - create two processes A and B
> - pipe from A to B
> - terminate A when B ends
I think you can do something like (untested):
import os, signal
pathToA = '/usr/bin/A'
pathToB = '/usr/bin/B'
# Create pipes
readA, writeB = os.pipe()
readB, writeA = os.pipe()
# Create process A
pidA = os.fork()
if pidA == 0: # child
os.dup2(readA.fileno(), 0) # set read pipe to stdin
os.dup2(writeA.fileno(), 1) # set write pipe to stdout
os.execl(pathToA)
# Create process B
pidB = os.fork()
if pidB == 0: # child
os.dup2(readB.fileno(), 0) # set read pipe to stdin
os.dup2(writeB.fileno(), 1) # set write pipe to stdout
os.execl(pathToB)
# Close file descriptors in the parent; it doesn't need them anymore
readA.close(); writeB.close(); readB.close(); writeA.close()
# Wait for B to terminate
os.waitpid(pidB, 0)
# Kill A (even if it has finished already... this might need a try/except)
os.kill(pidA, signal.SIGTERM)
# Wait for A (to avoid zombies)
os.waitpid(pidA, 0)
I've probably stuffed up some details, but I'm pretty sure that that's the
basic idea.
-Andrew.
More information about the Python-list
mailing list