简体   繁体   English

Java process.waitFor()不会阻塞该线程

[英]Java process.waitFor() does not block the thread

I'm building an application that should launch other applications on my windows PC. 我正在构建一个应该在我的Windows PC上启动其他应用程序的应用程序。 When the app is started my code should wait until I close that program to continue its execution. 当应用程序启动时,我的代码应该等到我关闭该程序以继续执行。

System.out.println("Starting ccleaner...");
Process p = Runtime.getRuntime().exec("C:\\Program Files\\CCleaner\\CCleaner64.exe");
System.out.println("Before wait");
p.waitFor(); 
//Here it should wait until the subprocess is 
// exited/the ccleaner programs exit button is clicked   
System.out.println("After wait");

All that happens is that it doesn't wait, it executes right away. 所有这一切都是它不会等待,它立即执行。 I looked up the waitFor() method in the documentation and it says: 我在文档中查找了waitFor()方法,它说:

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. 如果需要,使当前线程等待,直到此Process对象表示的进程终止。 This method returns immediately if the subprocess has already terminated. 如果子进程已终止,则此方法立即返回。 If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits. 如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。

And this seems pretty clear to me. 这对我来说似乎很清楚。 However I have looked at other questions regarding this issue on this site and found a couple of solutions that involves reading streams, but as I understand these are mostly when you have your own bat files you want to run. 但是我在这个网站上查看了有关此问题的其他问题,并找到了一些涉及读取流的解决方案,但据我所知,这些主要是当你有自己的bat文件时,你想要运行。 But I have tried these as well but not getting it to work. 但我也试过这些,但没有让它发挥作用。 Funny thing is that my code above is more or less identical to the one offered on tutorialpoints.com. 有趣的是,我上面的代码与tutorialpoints.com上提供的代码大致相同。

I've also tried using process.isAlive() but I can't seem to get that one working either. 我也尝试过使用process.isAlive()但我似乎无法让那个工作。

Does anyone know what I'm doing wrong here? 有谁知道我在这里做错了什么?

waitFor() does exactly what you expect. waitFor()完全符合您的期望。 Your understanding isn't wrong. 你的理解没有错。

I suspect the program you're running is indeed exiting immediately, causing waitFor() to return straight away. 我怀疑你正在运行的程序确实正在退出,导致waitFor()立即返回。 It may be starting one or more child processes that are doing the real work while the parent process exits. 它可能正在启动父进程退出时正在执行实际工作的一个或多个子进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM