Linux Pipe for Communication Between Java and C++ program

Pipe is neat. A pipe is a way to connect the output of one program to the input of another program without any temporary file.

This simple test contains a Java program and a C++ program. The output of Java program is used as input for “wc” command, and the output is then used by a C++ program.

Java program print a string simply.

 public class Main {
    public static void main(String args[]){
        System.out.println("result from Java program.");
    }
}

Compile the program by using javac Main.java, and a class file will be produced.

C++ program just accept a integer, and then output to console.

 
#include <iostream>
using namespace std;
int main(void)
{
  int number;
  cin >> number;
 
  cout << "Your number is " << number << "\n";
  return 0;
}

Compile the program by using command: g++ -o a accept.cpp. Change it’s access to executable by using command: chmod 755 a.

Now use the the command:

~/linuxPractice/java> java Main | wc -l | ./a
Your number is 1

Leave a Comment