java Runtime.exec运行交互式shell挂起

时间:2017-02-20 14:10:47

标签: java shell io runtime ipc

我尝试在java中执行windows命令cmd,用命令提供它并在控制台上打印输出或错误。但是,在打印横幅消息后,我的尝试挂起。这是代码。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Application {

    public static void main(String[] args) throws IOException, InterruptedException {

        Process exec = Runtime.getRuntime().exec("cmd");

        InputStream procOut = exec.getInputStream();
        InputStream procErrOut = exec.getErrorStream();
        OutputStream procIn = exec.getOutputStream();

        new StreamConsumer(procOut).run();
        new StreamConsumer(procErrOut).run();

        ByteArrayOutputStream byos = new ByteArrayOutputStream();
        byos.write("ping 1.1.1.1".getBytes());
        byos.writeTo(procIn);
        byos.flush();
        procIn.flush();

        int ret = exec.waitFor();
        System.out.printf("Process exited with value %d", ret);
    }

    public static class StreamConsumer implements Runnable {

        private InputStream input;

        public StreamConsumer(InputStream input) {
            this.input = input;
        }

        @Override
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}

这是输出

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
** program hangs **

为什么程序挂起而且没有ping执行(或打印)?我知道必须消耗流以避免挂起(我在单独的线程中执行),但它仍然挂起。我是否误解了输出流如何通过管道传输到交互式shell或者是什么问题?

1 个答案:

答案 0 :(得分:1)

您必须启动线程才能使用输出:

        new Thread(new StreamConsumer(procOut)).start();
        new Thread(new StreamConsumer(procErrOut)).start();