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