Java hangs when trying to close a ProcessBuilder OutputStream

后端 未结 3 1669
旧巷少年郎
旧巷少年郎 2020-12-21 16:58

I have the following Java code to start a ProcessBuilder, open an OutputStream, have the process write a string to an OutputStream, and then close the OutputStream. The who

3条回答
  •  情深已故
    2020-12-21 17:30

    When that happened to me it was because I hadn't read everything from the stream being written to by the process.

    The API docs for the java.lang.Process class say:

    The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

    I would try calling getInputStream() on the Process instance and writing a loop to read one byte at a time until it reaches EOF. And I'd do the same thing with getErrorStream() just in case the process is writing to stderr.

提交回复
热议问题