我正在用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();
}
}
Run Code Online (Sandbox Code Playgroud)
出于我理解的原因,该程序永远不会完成.如果"ipd/c dir"替换为ipconfig以及其他内容,则为真.
我可以看到使用ProcessExplorer java创建cmd进程.这个样本显然是一个简化; 在我的原始程序中,我发现如果我在一段时间后调用process.destroy()并检查cmd进程输出,则命令执行成功.
我已尝试使用Java 1.5和1.6的各种版本.我的操作系统是Windows XP Pro,SP 2.
Eri*_*lje 11
可能你只需要读取进程的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();
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此链接以获取解释.
您需要读取输入流.此外,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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4941 次 |
| 最近记录: |