当前位置:  开发笔记 > 编程语言 > 正文

从Java执行的Windows进程不会终止

如何解决《从Java执行的Windows进程不会终止》经验,为你挑选了2个好方法。

我正在用Java在Windows上创建一个进程.我的问题是这个过程不会终止.这是一个示例程序:

import java.io.IOException;

public class Test {

/**
 * @param args
 * @throws IOException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException,
        InterruptedException {
    Process process = Runtime.getRuntime().exec("cmd /c dir");
    process.waitFor();
    }
}

出于我理解的原因,该程序永远不会完成.如果"ipd/c dir"替换为ipconfig以及其他内容,则为真.

我可以看到使用ProcessExplorer java创建cmd进程.这个样本显然是一个简化; 在我的原始程序中,我发现如果我在一段时间后调用process.destroy()并检查cmd进程输出,则命令执行成功.

我已尝试使用Java 1.5和1.6的各种版本.我的操作系统是Windows XP Pro,SP 2.



1> Eric Petroel..:

可能你只需要读取进程的stdout和stderr,否则它将挂起,因为它的输出缓冲区已满.如果您将stderr重定向到stdout,这是最简单的,只是为了安全:

public static void main(String[] args) throws IOException,
                InterruptedException {
        String[] cmd = new String[] { "cmd.exe", "/C", "dir", "2>&1" };
        Process process = Runtime.getRuntime().exec(cmd);
        InputStream stdout = process.getInputStream();
        while( stdout.read() >= 0 ) { ; }
        process.waitFor();
    }
}



2> kgiannakakis..:

请参阅此链接以获取解释.

您需要读取输入流.此外,java进程不像dos shell那样工作.你需要自己传递参数:

String[] cmd = new String[3];
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = "dir";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

推荐阅读
贾志军
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有