Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Program A, is a c program that endlessly, receives input in stdin, process it and output it to stdout.

I want to write program B (in python) so it will reads A's output, and feed it back with whatever is needed. Note there must be only one instance of each of those programs, so given b1 and b2 which are instances of b instead of:

$ b1 | a | b2

I need to have

$ b1 | a | b1 

The following is the diagram of the final desired result:

alt text

like image 780
Tzury Bar Yochay Avatar asked Feb 25 '23 15:02

Tzury Bar Yochay


1 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 the two processes can communicate back and forth with each other via the pipes. It might also be a good idea to save the original sys.stdin and sys.stdout into other variables so that if you ever decide to terminate the subprocess, you can restore stdin and stdout to their original states (e.g. the terminal).

like image 53
Adam Rosenfield Avatar answered Feb 28 '23 03:02

Adam Rosenfield