• java父子进程通信


    1.利用进程的管道通信传输流

    2.子进程没有控制台,正常测试的时候也是没办法看到子进程的输出的,需要传到主线程

    3.测试主进程传参给子进程再传回来

    4.父进程启动子进程只要执行runtime.exec(cmd)就行了,但在linu下面,需要传入数组命令,否则一些特定字符会被当做参数

    5.比如"test.sh >> test.log",这种就不能exec直接执行,传入数组:{"/bin/sh","-c",cmd}

    子进程:

    import java.io.*;
    /**
     * Created by garfield on 2016/11/1.
     */
    public class TestCommand {
        public static void main(String[] args) throws IOException, InterruptedException {
            BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
            String line ;
            StringBuffer all = new StringBuffer();
            while((line = s.readLine()) != null){
                all.append(line);
            }
            System.out.println(all);
            s.close();
        }
    }

    父进程:

    import java.io.*;
    
    /**
     * Created by garfield on 2016/11/9.
     */
    public class TestCommunication {
        public static void main(String[] args) throws IOException, InterruptedException {
            Runtime run = Runtime.getRuntime();
            String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
            String cp = """ + System.getProperty("java.class.path");
            cp += File.pathSeparator + ClassLoader.getSystemResource("").getPath() + """;
            String cmd = java + " -cp " + cp + " com.TestCommand";
            Process p = run.exec(cmd);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            bw.write("999999");
            bw.flush();
            bw.close();
    
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String s;
            while ((s = br.readLine()) != null)
                System.out.println(s);
        }
    }

    父进程将99999传给子进程,又在控制台输出:

    999999
  • 相关阅读:
    离散数学概论
    Linux内核分析
    程序的本质
    常见bug分析
    java编程思想--学习心得
    领域特定语言--心得
    Linux下网卡配置
    ubuntu下安装python的gevent模块遇到的一个问题
    二分图的最小点覆盖和最大独立集
    win7通过ssh远程登录mininet虚拟机,运行wireshark并通过x11在宿主机显示图形界面
  • 原文地址:https://www.cnblogs.com/garfieldcgf/p/6150196.html
Copyright © 2020-2023  润新知