package euler; import java.io.*; import java.util.*; public class Process implements Runnable { String[] cm = null; String in = null; String out = null; String err = null; PrintStream op = null; PrintStream ep = null; java.lang.Process pr = null; boolean running = false; int ev = 0; ArrayList file_list; private static String run_dir; public Process(String cmd, String inp) { StringTokenizer t = new StringTokenizer(cmd); cm = new String[t.countTokens()]; for (int i = 0; t.hasMoreTokens(); i++) { cm[i] = t.nextToken(); } in = inp; } public Process(String[] cmd, String inp) { cm = cmd; in = inp; } public Process(String[] cmd, String inp, PrintStream ops, PrintStream eps) { cm = cmd; in = inp; op = ops; ep = eps; } public int execute(long ttl) { start(); try { while (isRunning() && ttl > 0) { Thread.sleep(5); ttl = ttl - 5; } } catch (Exception e) { throw new RuntimeException(e); } if (ttl <= 0) { stop(); throw new RuntimeException("No proof found: timeout"); } if (err != null) { stop(); throw new RuntimeException(err); } return ev; } public void run() { try { if (run_dir != null) { pr = Runtime.getRuntime().exec(cm, null, new File(run_dir)); } else { pr = Runtime.getRuntime().exec(cm); } InputStream inputStream = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "UTF8"); BufferedReader br = new BufferedReader(isr); BufferedOutputStream bos = new BufferedOutputStream(pr.getOutputStream()); PrintWriter pwr = new PrintWriter(new OutputStreamWriter(bos, "UTF8"), true); DataInputStream des = new DataInputStream(pr.getErrorStream()); ProcessErr pe = new ProcessErr(des, ep); pe.start(); if (in != null) { pwr.print(in); } pwr.close(); String co = null; int cnt = 0; while(inputStream.available() == 0 && cnt < 100) { Thread.sleep(5); cnt++; } if (op != null) { while ((co = br.readLine()) != null) { op.println(co); } } else { StringBuilder sb = new StringBuilder(); while ((co = br.readLine()) != null) { sb.append(co).append('\n'); } out = sb.toString(); } while (pe.isRunning()) { Thread.sleep(5); } Thread.sleep(5); err = pe.getError(); des.close(); br.close(); ev = pr.waitFor(); pr.destroy(); pr.getInputStream().close(); pr.getOutputStream().close(); pr.getErrorStream().close(); pr = null; Thread.yield(); } catch (Exception e) { err = e.toString(); } finally { running = false; } } public void start() { new Thread(this).start(); running = true; } public void stop() { if (pr != null) { pr.destroy(); } running = false; } public boolean isRunning() { return running; } public String getOutput() { return out; } public void setFileList(ArrayList fl) { file_list = fl; } public ArrayList getFileList() { return file_list; } public static void setRunDirectory(String run_dir) { Process.run_dir = run_dir; } public static String getRunDirectory() { return Process.run_dir; } }