How can I make these two processes (programs) talk to each other directly using pipes?

Program A is a c-program that, endlessly, receives input in stdin, processes and outputs it to stdout.

I want to write program B (in python) so that it reads the output and returns it with everything necessary. Please note that there should be only one instance of each of these programs, therefore b1 and b2 are given, which are instances of b, and not:

$ b1 | a | b2 

I need to have

 $ b1 | a | b1 

Below is a diagram of the final desired result:

alt text

+4
source share
2 answers

Use the subprocess.Popen class to create a subprocess for program A. For example:

 import subprocess import sys # Create subprocess with pipes for stdin and stdout progA = subprocess.Popen("a", stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Reassign the pipes to our stdin and stdout sys.stdin = progA.stdout sys.stdout = progA.stdin 

Now two processes can interact with each other through pipes. It might also be a good idea to store the original sys.stdin and sys.stdout in other variables so that if you ever decide to terminate the subprocess, you can restore stdin and stdout to their original states (e.g., terminal).

+6
source

For those who come here from Google: actually a very good way to use named pipes:

first create 2 names:

 mkfifo pipe1 mkfifo pipe2 

then run this:

 echo -nx | cat - pipe1 > pipe2 & cat <pipe2 > pipe1 

this will cause the cat commands to copy the letter x all the time to each other. So now you can freely use your own programs instead of cats to process input and output. This is not limited to python. You can also connect a Java program using a C ++ program.

For example, if your programs are called A.py and B.py, then the initial command:

 echo -nx | ./A.py - pipe1 > pipe2 & ./B.py <pipe2 > pipe1 
+1
source

All Articles