ProcessBuilder的正确使用
经过研究,我注意到使用 java 的 ProcessBuilder 的“正确”方法是生成另外两个线程来管理新创建进程的 stdout/stderr 的吞噬,这样它就不会挂起,如下所示: javaworld 文章
但是这个让我想知道两个问题—— 1.) 为什么需要单独的进程而不是让父进程吞噬 stdout,然后依次吞噬 stderr?
2.) 此外,如果您要将流重定向到 stdout,那么让父进程吞下 stdout 流,然后不必担心死锁是否可以接受?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意你的条款。 线程不是进程。
因为子进程可以同时写入两者,当
stderr
的缓冲区已满时,您会遇到死锁(子进程等待父进程读取stderr
,父进程等待子进程关闭stdout
)。没有。如果子进程也需要
stdin
,那么您必须在主线程中处理stdin
并通过额外的线程读取合并的输出流,否则可能会再次出现死锁(子进程等待)父进程读取输出流,父进程等待子进程读取stdin
上的数据。Mind your terms. Threads aren't processes.
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 readstderr
, parent waits for child to closestdout
).No. If the child process also needs
stdin
, then you must handlestdin
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 onstdin
).