0

I'm trying to pass commands to commandLine using streams. I used ProcessBuilder to start the process. After running the code, commandLine pops up but the strings are not passed to commandLine. I have created separate threads for input and out streams, The process never gets terminated.

        public static void main(String[] args) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","start");
    pb.redirectOutput(Redirect.INHERIT);
    pb.redirectError(Redirect.INHERIT);
    Process p = pb.start();
    final InputStream is = p.getInputStream();
    OutputStream os = p.getOutputStream();


    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {

                PrintWriter s = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
                s.write("1");
                s.write("\n");
                s.flush();
                System.out.println("Pass written");
            }
            catch(Exception e)
            {
                System.out.println("Exception raised in writer thread"+ e);
            }
        }
    }).start();

    new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String s;
                while (( s=reader.readLine()) != null) {
                    System.out.println(s);
                }
            }
            catch(Exception e)
            {
                System.out.println("Exception raised in reader thread"+ e);
            }
        }
    }).start();

    int returnVal = p.waitFor();
    System.out.println("Process ended with return val "+ returnVal);

}
Rajesh
  • 1
  • 1
  • I think your specific problem is using `Redirect.INHERIT` instead of `Redirect.PIPE`. – jkinkead Feb 03 '17 at 22:14
  • Thanks for the help. Although, even after changing it to Redirect.PIPE, no commands were passed to commandline. OutputStream seems to have no impact. – Rajesh Feb 03 '17 at 22:50

0 Answers0