Java 父子进程通信

由父进程创建子进程,收发消息


package org.tango.process.parent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tango.process.signal.Signal;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Scanner;

/**
 * Created by tango on 14-7-3.
 */
public class Main {
    private static final Log LOG = LogFactory.getLog(Main.class);
    private static final Signal SIGNAL = new Signal();

    public static void main(String[] args) throws IOException {
        try {
            startProcess("java", "org.tango.process.child.SubMain", "/Users/tango/Java/Application/restruct/tango-process/tango-process-child/target/classes/", null);
            Scanner scanner = new Scanner(System.in);

            while (true) {
                //
                LOG.debug("please input message,[quit | exit]: exit program");
                String next = scanner.next();
                if ("quit".equals(next) || "exit".equals(next)) {
                    break;
                }
                boolean send = SIGNAL.send(next);
                LOG.debug("send message : " + next + " /".concat(String.valueOf(send)));
                String receive = SIGNAL.receive();
                LOG.debug("receive message : " + receive);
            }
            LOG.debug("finish,will shutdown program");
        } catch (Exception err) {
            err.printStackTrace();
        }
    }

    private static Process startProcess(String command, String args, String directory, String classPath) throws IOException, NoSuchFieldException, IllegalAccessException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(command, args);
        //
        LOG.debug("create sub process of ".concat(command).concat(" ").concat(args));
        builder.directory(new File(directory));
        LOG.debug("setting work directory successful : ".concat(directory));
        if (classPath != null) {
            Map<String, String> environment = builder.environment();
            environment.put("CLASSPATH", environment.get("CLASSPATH").concat(":").concat(classPath));
            LOG.debug("process environment : ".concat(environment.toString()));
        }
        //
        final Process process = builder.start();
        Field pidField = process.getClass().getDeclaredField("pid");
        pidField.setAccessible(true);
        Object pid = pidField.get(process);
        LOG.debug("start process successful : pid/".concat(pid.toString()));
        //
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                process.destroy();
            }
        });
        LOG.debug("setting shutdown hook successful");
        //
        SIGNAL.setOut(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())));
        LOG.debug("converter out successful");
        SIGNAL.setIn(new BufferedReader(new InputStreamReader(process.getInputStream())));
        LOG.debug("converter in successful");
        SIGNAL.setErr(new BufferedReader(new InputStreamReader(process.getErrorStream())));
        LOG.debug("converter err successful");
      /*  BufferedReader err = SIGNAL.getErr();
        System.out.println("err = " + err.readLine());*/
        return process;
    }
}
package org.tango.process.child;

import org.tango.process.signal.Signal;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by tango on 14-7-5.
 */
public class SubMain {
    private static final Signal SIGNAL = new Signal();

    public static void main(String[] args) throws Exception {
        SIGNAL.setIn(new BufferedReader(new InputStreamReader(System.in)));
        SIGNAL.setOut(new BufferedWriter(new OutputStreamWriter(System.out)));
        //
        ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        String receive = SIGNAL.receive();
                        if (receive != null) {
                            SIGNAL.send(receive.concat(" ").concat("too"));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
package org.tango.process.signal;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by tango on 14-7-3.
 */
public class Signal {
    private BufferedReader in;
    private BufferedWriter out;
    private BufferedReader err;

    public boolean send(String message) throws IOException {
        try {
            out.write(message);
            out.write("\r\n");
            out.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public String receive() throws IOException {
        String message = in.readLine();
        return message;
    }

    public String valid() throws IOException {
        String message = err.readLine();
        return message;
    }

    public BufferedReader getIn() {
        return in;
    }

    public void setIn(BufferedReader in) {
        this.in = in;
    }

    public BufferedWriter getOut() {
        return out;
    }

    public void setOut(BufferedWriter out) {
        this.out = out;
    }

    public BufferedReader getErr() {
        return err;
    }

    public void setErr(BufferedReader err) {
        this.err = err;
    }
}

代码清单如下:

|____tango-process

| |____pom.xml

| |____tango-process-child

| | |____pom.xml

| | |____src

| | | |____main

| | | | |____java

| | | | | |____org

| | | | | | |____tango

| | | | | | | |____process

| | | | | | | | |____child

| | | | | | | | | |____SubMain.java

| | | | | | | | |____signal

| | | | | | | | | |____Signal.java

| | | | |____resources

| | | |____test

| | | | |____java

| |____tango-process-parent

| | |____pom.xml

| | |____src

| | | |____main

| | | | |____java

| | | | | |____org

| | | | | | |____tango

| | | | | | | |____process

| | | | | | | | |____parent

| | | | | | | | | |____Main.java

| | | | | | | | |____signal

| | | | | | | | | |____Signal.java

| | | | |____resources

| | | | | |____log4j.properties


你可能感兴趣的:(java,管道,父子进程通信)