Skip to content
Advertisement

Inter process communication from python to cpp program

Suppose there are 3 files: f1.cpp, f2.py, f3.cpp. I am running the command on linux terminal as follows:

$./f1.out | python3 f2.py | ./f3.out

The output of f1 goes perfectly into the input of f2. Also, f2’s output goes perfectly into f3. I am displaying the output in f3. f1 generates input for f2 after a particular interval. In this interval, I need to enter a user input in f3 file so that it can give an output accordingly during that pause. I tried debugging my code and I found that although my final output without user input is generated by f3, my user input is not being read. Somebody help!!

Advertisement

Answer

Since you have already declared from your command that f3 should take input from f2’s output and f2 should take input from f1’s output, there is no straightforward way to give console input to f3 now.

The best way here would be (assuming you are only the author of f1 and f2 also) you can just read that user input in f1 only and immediately print it

cin >> input;
cout << input;

so that it will be passed to f2’s input. You can do a similar thing in f2 also

inp = str(input)
print(inp)

hence passing that to f3 as you wanted.

But if you don’t want to do it this way or if you are not the author of f1 and f2, I would suggest you launch f3 in a separate terminal window and use a named pipe(FIFO) for communication between f2 and f3. Since the communication would be happening through a FIFO, the stdin would still be pointing to the keyboard and you can type input to f3.

Edit

Another way you can do it is(although, I’m not sure how healthy this is), you can spawn a new thread before sleeping. Take input in new thread and terminate that new thread once input is taken. The new thread will be running as long as input is not given. In the main thread sleep for 5 seconds and when main thread wakes up, forcefully terminate the new thread using something like pthread_kill.

Advertisement