在继续使用 Java 之前等待进程完成 [英] Wait for process to finish before proceeding in Java

查看:27
本文介绍了在继续使用 Java 之前等待进程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本质上,我正在制作一个小程序,用于安装一些软件,然后运行一些基本命令来准备该程序.然而,发生的事情是程序开始安装,然后立即移动到以下几行(注册、更新等).当然,在完全安装之前这不会发生,所以我想找到一种在运行第二个进程之前等待第一个进程的方法.例如,

Essentially, I'm making a small program that's going to install some software, and then run some basic commands afterwards to prep that program. However, what is happening is that the program starts its install, and then immediately moves on to the following lines (registration, updates, etc). Of course, that can't happen until it's fully installed, so I'd like to find a way of waiting on the first process before running the second. For example,

    Main.say("Installing...");
    Process p1 = Runtime.getRuntime().exec(dir + "setup.exe /SILENT");
    //Wait here, I need to finish installing first!
    Main.say("Registering...");
    Process p2 = Runtime.getRuntime().exec(installDir + "program.exe /register aaaa-bbbb-cccc");
    Main.say("Updating...");
    Process p4 = Runtime.getRuntime().exec(installDir + "program.exe /update -silent");

推荐答案

调用 Process#waitFor().它的 Javadoc 说:

Call Process#waitFor(). Its Javadoc says:

如果需要,使当前线程等待,直到由这个 Process 对象表示的进程终止.

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

奖励:您获得子进程的退出值.所以你可以用代码0检查它是否成功退出,或者是否发生错误(非零退出代码).

Bonus: you get the exit value of the subprocess. So you can check whether it exited successfully with code 0, or whether an error occured (non-zero exit code).

这篇关于在继续使用 Java 之前等待进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆