shababhsiddique
shababhsiddique

Reputation: 911

Problem getting output and passing input to a executing process running under java

I am trying to call a simple program test.exe which is as simple as-

int main()
{
    int a;
    cout<<"Welcome\n";
    while(cin>>a&&a!=0)
    cout<<"you entered "<<a<<endl;
}

I want to run it from a java program as a process, and send+recieve i/o from it. I am using the process with 2 threads as follows-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Processproblem {

    public static void main(String[] args)throws IOException, InterruptedException {
        final Process process;
          try {
            process = Runtime.getRuntime().exec("test.exe");
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }

           new Thread(new Runnable() {
            public void run() {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                try {
                    while ((line = br.readLine()) != null) {
                        System.out.println("[OUT] " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


      new Thread(new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[1024];
                int reading=0;
                System.out.println(reading);
                BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

                while(reading!=-1)
                {
                     reading= System.in.read(buffer);
                     for(int i = 0; i < buffer.length; i++) {
                        int intValue = new Byte(buffer[i]).intValue();
                        if (intValue == 0) {
                            reading = i;
                            break;
                        }
                        else
                        {
                            bw.append((char)intValue);
                        }
                    }
                      bw.newLine();
                        bw.flush();

                }

            } catch (Exception e) {
            }
        }
    }
            ).start();
    }
}

But they are not working as expected. When i run the program it just shows the "Welcome\n" message and then stops for input. When i give a integer and press enter in the java console it does nothing.

What am I doing wrong? They are two separate threads so why are they blocking each other? Is there any problem in my concept?

Upvotes: 2

Views: 592

Answers (1)

MByD
MByD

Reputation: 137362

The program waits for your input. Grab the process output stream (using getOutputStream) and write to it.

Upvotes: 3

Related Questions