I'm putting together a multi-language system, but am running into issues with orphaned processes.

My code consists of a Python program calling a Java program, with piped communication between the two programs; the Java program is persistent, not just a one-off run. Everything is generally working, but I need the Java program to close if the Python program prematurely exits.

I think the best way to do this is to have the Java program close itself if it can't detect the stdin pipe between the programs, but I can't figure out to do this.

Relevant Python code:

javaInterface = subprocess.Popen(["pathtojavaprogram"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

Relevant Java code; I want the program to exit if it can't read from stdin, but I think that some blocking issues with the readLine() function are coming into play:

String stdinStr = "";
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

while(true){
    try{
        stdinStr = stdin.readLine();
    }
    catch(java.lang.Exception e){
        System.exit(0);
    }
    //Do stuff with the stdinStr data
}
有帮助吗?

解决方案

This was answered in the comments by trutheality, but I wanted to mark this as answered.

The readLine() function returns null whenever the pipe exits, so checking for that allows you to close the subprocess properly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top