Correct Usage of ProcessBuilder

痴心易碎 提交于 2019-12-22 10:52:07

问题


After researching I have noticed that the "correct" way to use java's ProcessBuilder is to spawn two other threads to manage gobbling up the stdout/stderr of the newly created process so that it doesn't hang as is shown here : javaworld article

But this has left me wondering about 2 questions- 1.) Why exactly are seperate processes needed instead of having the parent process gobble up the stdout and then sequentially the stderr?

2.) In addition, if you were to redirect the streams to both go to stdout would it be acceptable to just have the parent process swallow the stdout stream, and then not have to worry about deadlocks?


回答1:


Mind your terms. Threads aren't processes.

  1. Because the child could write to both and you would get a deadlock when the buffer for stderr is full (child waits for parent to read stderr, parent waits for child to close stdout).

  2. No. If the child process also needs stdin, then you must handle stdin in your main thread and read the merged output streams via an extra thread or you could have deadlocks again (child waits for parent to read the output stream and the parent waits for the child to read the data on stdin).



来源:https://stackoverflow.com/questions/3054531/correct-usage-of-processbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!