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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM