Adding some more judges, here and there.
[and.git] / NEERC / central / run2.java
blob877f31b9d63a9c60f249da50dc70656789880057
1 import java.util.Arrays;
2 import java.io.*;
4 /**
5 * Simple tool to start two processes piped into each other.
6 *
7 * @author Roman Elizarov
8 */
9 public class run2 {
10 public static void main(String[] args) throws IOException, InterruptedException {
11 if (args.length < 2) {
12 System.err.println("Usage: run2 <interaction-exe> <main-exe> [<main-process-args> ...]");
13 return;
15 run2 instance = new run2(args);
16 try {
17 instance.go();
18 } finally {
19 instance.killThemAll();
23 private final Process p1;
24 private final Process p2;
26 private run2(String[] args) throws IOException {
27 ProcessBuilder pb1 = new ProcessBuilder(args[0]);
28 ProcessBuilder pb2 = new ProcessBuilder(Arrays.asList(args).subList(1, args.length).toArray(new String[args.length - 1]));
29 pb1.redirectErrorStream(true);
30 pb2.redirectErrorStream(true);
31 p1 = pb1.start();
32 p2 = pb2.start();
35 private void go() throws InterruptedException {
36 new Redirector(p1.getInputStream(), p2.getOutputStream()).start();
37 new Redirector(p2.getInputStream(), p1.getOutputStream()).start();
38 p2.waitFor();
39 p1.destroy();
40 p1.waitFor();
43 private void killThemAll() {
44 p1.destroy();
45 p2.destroy();
48 private class Redirector extends Thread {
49 final InputStream in;
50 final OutputStream out;
52 private Redirector(InputStream in, OutputStream out) {
53 this.in = in;
54 this.out = out;
57 public void run() {
58 byte[] buf = new byte[4096];
59 int len;
60 try {
61 while ((len = in.read(buf)) > 0) {
62 out.write(buf, 0, len);
63 out.flush();
65 } catch (IOException e) {
66 System.err.println(e.toString());
67 killThemAll();