简体   繁体   English

调用程序退出/崩溃时关闭Java子进程

[英]Close Java subprocess when calling program exits/crashes

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; 我的代码包含一个调用Java程序的Python程序,两个程序之间通过管道通信。 the Java program is persistent, not just a one-off run. Java程序是持久性的,而不仅仅是一次性运行。 Everything is generally working, but I need the Java program to close if the Python program prematurely exits. 一切正常,但是如果Python程序过早退出,我需要关闭Java程序。

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. 认为 ,执行此操作的最佳方法是,如果无法检测到程序之间的stdin管道,则关闭Java程序,但我不知道该怎么做。

Relevant Python code: 相关的Python代码:

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

Relevant Java code; 相关的Java代码; 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: 我希望程序无法从stdin中读取时退出,但是我认为readLine()函数的某些阻塞问题正在发挥作用:

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. 每当管道退出时, readLine()函数都将返回null ,因此进行检查可以使您正确关闭子流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM