如何以严格的顺序启动多个命令(使用ProcessBuilder
或Runtime.exec
- 什么是最简单的)?
例:
Process process1 = Runtime.getRuntime().exec("myFirstCommand");
process1.waitFor();
Runtime.getRuntime().exec("mySecondCommand");
工作正常,但是,我想只调用一次Runtime.exec/ProcessBuilder.start()
并立即返回。所以基本上它应该工作,好像我从命令行工具调用包含这两个命令的批处理文件(我不能做,因为这两个命令是动态生成的)。在mySecondCommand
完成之前,不得启动myFirstCommand
!
有任何想法吗?
如果你想只运行第二个命令,如果第一个命令成功,你可以做类似的事情
if (process1.exitValue() == 0) {
Runtime.getRuntime().exec("mySecondCommand");
}
您说“它应该像我从命令行工具调用包含这两个命令的批处理文件一样工作”。所以这样做对我有用:
String command = "someComand someParam";
command+= "\nsomeOtherCommand someOtherParam";
String commandname=Utilities.getRandomNameOfLengthLowerCase(10) + ".sh";
command+= "\nrm " + pathToContent + commandname;
Utilities.writeFile(command, pathToContent + commandname);
Process actProcess = Runtime.getRuntime().exec("chmod 777 " + pathToContent + commandname);
actProcess.waitFor();
actProcess = Runtime.getRuntime().exec(pathToContent + commandname);