Run external program from Java, read output, allow interruption

前端 未结 5 1133
孤独总比滥情好
孤独总比滥情好 2020-11-29 08:18

I want to launch a process from Java, read its output, and get its return code. But while it\'s executing, I want to be able to cancel it. I start out by launching the proce

5条回答
  •  忘掉有多难
    2020-11-29 09:09

    What would make you decide to kill the process -- an asynchronous event (such as input from the user), or a synchronous event (e.g., the process has done what you wanted it to do)? I'm guessing it's the former -- input from the user makes you decide to cancel the subprocess.

    Also, how much output do you expect the subprocess to produce? If it's a lot, then the subprocess may block if you don't read from its output stream quickly enough.

    Your situation may vary, but it seems that you're likely going to need at least two different threads -- one to decide whether to cancel the process, and one that handles the output from the subprocess.

    Have a look here for a bit more detail: http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2

提交回复
热议问题