1 // Create a process and pipe data through it. waitFor() the process 2 // in a different thread than the one that created it. 3 import java.io.BufferedReader; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import java.io.OutputStream; 7 import java.io.PrintStream; 8 9 10 public class Process_3 implements Runnable 11 { 12 Process p; 13 run()14 public void run() 15 { 16 try 17 { 18 Runtime r = Runtime.getRuntime(); 19 String[] a = { "sed", "-e", "s/Hello/Goodbye/" }; 20 synchronized (this) 21 { 22 p = r.exec(a); 23 this.notifyAll(); 24 } 25 OutputStream os = p.getOutputStream(); 26 PrintStream ps = new PrintStream(os); 27 ps.println("Hello World"); 28 ps.close(); 29 } 30 catch (Exception ex) 31 { 32 System.out.println(ex.toString()); 33 System.exit(1); 34 } 35 } 36 main(String[] args)37 public static void main(String[] args) 38 { 39 try 40 { 41 Process_3 p3 = new Process_3(); 42 Thread t = new Thread(p3); 43 t.start(); 44 synchronized (p3) 45 { 46 while (p3.p == null) 47 p3.wait(); 48 } 49 50 InputStream is = p3.p.getInputStream(); 51 InputStreamReader isr = new InputStreamReader(is); 52 BufferedReader br = new BufferedReader(isr); 53 String result = br.readLine(); 54 if (! "Goodbye World".equals(result)) 55 { 56 System.out.println("bad 1"); 57 return; 58 } 59 result = br.readLine(); 60 if (result != null) 61 { 62 System.out.println("bad 2"); 63 return; 64 } 65 int c = p3.p.waitFor(); 66 System.out.println(c == 0 ? "ok" : "bad 3"); 67 } 68 catch (Exception ex) 69 { 70 System.out.println(ex.toString()); 71 } 72 } 73 } 74