-1

Following works on my win8.1 but not on Windows Server 2008. If I close the outputstream then it works on windows server 2008 but that's not what I want. I want to keep open the wmic and process multiple commands.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class WMI {

    BufferedWriter writer;

    public WMI() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("wmic");
            new Thread(new Reader(process.getInputStream())).start();
            new Thread(new Reader(process.getErrorStream())).start();
            writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void execute(String cmd) {
        try {
            writer.write(cmd);
            writer.newLine();
            writer.flush();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    private static class Reader implements Runnable {
        private BufferedReader reader;

        public Reader(InputStream is) {
            this.reader = new BufferedReader(new InputStreamReader(is));
        }

        @Override
        public void run() {
            String line = null;
            try {
                while((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WMI wmi = new WMI();
        wmi.execute("service get name");
    }
}
DROP TABLE users
  • 1,955
  • 14
  • 26
Deepak Agarwal
  • 907
  • 6
  • 21

1 Answers1

0

Make sure your program (JVM) does not stop before the reader threads get a chance to print anything. Along the lines of:

 Thread stdoutReader = new Thread(new Reader(process.getInputStream()));
 stdoutReader.setDaemon(false);
 stdoutReader.start():

Similarly for the stderr reader. The default (daemon on/off) may be different for the different Windows platforms.

Also make sure the command service get name is valid and does not require further input.

Jukka
  • 4,583
  • 18
  • 14
  • Actually, the same code works fully on windows8 but not on Windows Server 2008. Since I am already spawning a thread for reading and writing purpose so I don't think reader is not getting chance. – Deepak Agarwal Jan 01 '14 at 18:41