父进程和子进程之间的通信

时间:2016-11-01 11:01:06

标签: java multithreading parent-child child-process

我有一个充当父进程的类。在运行期间,它会创建许多子进程并同时运行它们。每个子进程基本上都是一个HTTP客户端,它连接到一个服务并从中提取数据。

目前,如果其中一个子进程因任何原因停止工作,则父进程通过重新启动相同的子进程来重新建立连接。

子进程的断开可能是由几件事引起的。我想将子进程断开连接到父进程的原因,并让父进程根据断开的原因(套接字读取失败,404未找到,401未授权等)进行相应的操作。

有可能吗?最短/最好的方法是什么? 这是我的父类:

public class Parent {
public static void main(String[] args){
    List<Process> PRlist = new ArrayList<Process>();
    List<String[]> commandsList = new ArrayList<String[]>();
    DateTimeFormatter frmt = DateTimeFormatter.ofPattern("hh:mm:ss");

    if (args.length == 2 && args[0].matches("-f")){
        String dir = System.getProperty("user.dir");
        String path = dir + "/" + args[1];
        try {
            FileReader fr = new FileReader(path);
            BufferedReader bf = new BufferedReader(fr);

            String line = "";
            while ((line = bf.readLine()) != null){
                String[] tk = line.split(" ");
                String[] cmd = {"java", "-jar", "Child.jar", "-a", tk[0], "-p", tk[1],
                        "-u", tk[2], "-pw", tk[3], "-m", tk[4], "-s", tk[5]};
                Process pr = new ProcessBuilder().inheritIO().command(cmd).redirectInput(Redirect.INHERIT).start();
                PRlist.add(pr); commandsList.add(cmd);
            }
        } 
        catch (FileNotFoundException ex) {ex.printStackTrace();} 
        catch (IOException ex) {ex.printStackTrace();}

        int streamnum = PRlist.size();

        while (true){
            for (int i = 0; i < streamnum; i++){
                if (!PRlist.get(i).isAlive()){
                    PRlist.get(i).destroy();
                    PRlist.remove(i);
                    try {
                        Process PR = new ProcessBuilder().inheritIO().command(commandsList.get(i)).redirectInput(Redirect.INHERIT).start();
                        System.out.println(commandsList.get(i)[12] + " stream re-established at " + LocalDateTime.now().format(frmt));
                        PRlist.add(i,PR);
                    } catch (IOException ex) {ex.printStackTrace();}
                }
            }

            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {ex.printStackTrace();}
        }
    } else {
        System.out.println("No stream file was specified.");
    }
}}

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

也许你可以使用方法

**public ProcessBuilder.Redirect redirectError()**
Returns this process builder's standard error destination. Subprocesses   subsequently started by this object's start() method redirect their standard error to this destination. The initial value is Redirect.PIPE.
Returns:
this process builder's standard error destination

或者

public abstract int exitValue()
Returns the exit value for the subprocess.
Returns:
the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
Throws:
IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated

答案 1 :(得分:0)

例如

喜欢

if (!PRlist.get(i).isAlive()){
    int exitCode=PRlist.get(i).exitValue();
    //Do something with exitValue

    PRlist.get(i).destroy();
    PRlist.get(i).destroy();
    PRlist.remove(i);
    try {
        Process PR = new ProcessBuilder().inheritIO().command(commandsList.get(i)).redirectInput(Redirect.INHERIT).start();
        System.out.println(commandsList.get(i)[12] + " stream re-established at " + LocalDateTime.now().format(frmt));
         PRlist.add(i,PR);
         } catch (IOException ex) {ex.printStackTrace();}
         }

errorStream的示例可能更复杂,但想法是查看通过文本处理在errorStream中发布的异常。

答案 2 :(得分:0)

好的,使用Java Threads你可以这样做:

class MyThreadedApp {

    // main() here

    /**
     * Starting a new thread
     */
    private void start() {
        new Thread(() -> {
            try {
                new Worker().run();
            } catch (Exception ex) {
                threadEnded(ex);
            }
        }).start();
    }

    /**
     * Handle errors
     * 
     * @param ex Error
     */
    private void threadEnded(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

/**
 * My worker thread
 */
class Worker {

    void run() throws IOException {
        // Do my stuff here
    }
}

这是展示数据流的基本示例。在实践中,你可以使用@lscoughlin提到的技术。