diff options
author | Jon Bratseth <bratseth@yahoo-inc.com> | 2016-06-15 23:09:44 +0200 |
---|---|---|
committer | Jon Bratseth <bratseth@yahoo-inc.com> | 2016-06-15 23:09:44 +0200 |
commit | 72231250ed81e10d66bfe70701e64fa5fe50f712 (patch) | |
tree | 2728bba1131a6f6e5bdf95afec7d7ff9358dac50 /vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java |
Publish
Diffstat (limited to 'vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java')
-rw-r--r-- | vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java b/vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java new file mode 100644 index 00000000000..bb2909b346a --- /dev/null +++ b/vespajlib/src/main/java/com/yahoo/system/ProcessExecuter.java @@ -0,0 +1,56 @@ +// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.system; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import com.yahoo.collections.Pair; + +/** + * Executes a system command synchronously. + * + * @author <a href="mailto:bratseth@yahoo-inc">Jon S Bratseth</a> + */ +public class ProcessExecuter { + + /** + * Executes the given command synchronously without timeout. + * @return Retcode and stdout/stderr merged + */ + public Pair<Integer, String> exec(String command) throws IOException { + StringTokenizer tok = new StringTokenizer(command); + List<String> tokens = new ArrayList<>(); + while (tok.hasMoreElements()) tokens.add(tok.nextToken()); + return exec(tokens.toArray(new String[0])); + } + + /** + * Executes the given command synchronously without timeout. + * @param command tokens + * @return Retcode and stdout/stderr merged + */ + public Pair<Integer, String> exec(String[] command) throws IOException { + ProcessBuilder pb = new ProcessBuilder(command); + StringBuilder ret = new StringBuilder(); + pb.environment().remove("VESPA_LOG_TARGET"); + pb.redirectErrorStream(true); + Process p = pb.start(); + InputStream is = p.getInputStream(); + while (true) { + int b = is.read(); + if (b==-1) break; + ret.append((char)b); + } + int rc=0; + try { + rc = p.waitFor(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return new Pair<>(rc, ret.toString()); + } + +} |