java.lang.ProcessBuilder.redirectError()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(169)

本文整理了Java中java.lang.ProcessBuilder.redirectError()方法的一些代码示例,展示了ProcessBuilder.redirectError()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ProcessBuilder.redirectError()方法的具体详情如下:
包路径:java.lang.ProcessBuilder
类名称:ProcessBuilder
方法名:redirectError

ProcessBuilder.redirectError介绍

[英]Indicates whether the standard error should be redirected to standard output. If redirected, the Process#getErrorStream() will always return end of stream and standard error is written to Process#getInputStream().
[中]指示是否应将标准错误重定向到标准输出。如果重定向,进程#getErrorStream()将始终返回流的末尾,标准错误将写入进程#getInputStream()。

代码示例

代码示例来源:origin: stackoverflow.com

ProcessBuilder pb = new ProcessBuilder("yourcommand");
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();

代码示例来源:origin: ming1016/study

@Nullable
public Process startInterpreter(String pythonExe) {
  Process p;
  try {
    ProcessBuilder builder = new ProcessBuilder(pythonExe, "-i", jsonizer);
    builder.redirectErrorStream(true);
    builder.redirectError(new File(parserLog));
    builder.redirectOutput(new File(parserLog));
    builder.environment().remove("PYTHONPATH");
    p = builder.start();
  } catch (Exception e) {
    _.msg("Failed to start: " + pythonExe);
    return null;
  }
  return p;
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testCommandWrapperCommand() {
 CommandWrapper commandWrapper = CommandWrapper.create();
 commandWrapper.setCommand(COMMAND);
 ProcessBuilder processBuilder = commandWrapper.getBuilder();
 if (BaseEmulatorHelper.isWindows()) {
  assertEquals(WIN_COMMAND, processBuilder.command());
 } else {
  assertEquals(UNIX_COMMAND, processBuilder.command());
 }
 assertNull(processBuilder.directory());
 assertFalse(processBuilder.redirectErrorStream());
 assertEquals(ProcessBuilder.Redirect.PIPE, processBuilder.redirectError());
}

代码示例来源:origin: prestodb/presto

public static Pager create(List<String> command)
{
  try {
    Process process = new ProcessBuilder()
        .command(command)
        .redirectOutput(ProcessBuilder.Redirect.INHERIT)
        .redirectError(ProcessBuilder.Redirect.INHERIT)
        .start();
    return new Pager(process.getOutputStream(), process);
  }
  catch (IOException e) {
    System.err.println("ERROR: failed to open pager: " + e.getMessage());
    return createNullPager();
  }
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testCommandWrapperDirectory() {
 CommandWrapper commandWrapper = CommandWrapper.create();
 commandWrapper.setCommand(COMMAND);
 commandWrapper.setDirectory(DIRECTORY);
 ProcessBuilder processBuilder = commandWrapper.getBuilder();
 if (BaseEmulatorHelper.isWindows()) {
  assertEquals(WIN_COMMAND, processBuilder.command());
 } else {
  assertEquals(UNIX_COMMAND, processBuilder.command());
 }
 assertEquals(DIRECTORY, processBuilder.directory().toPath());
 assertFalse(processBuilder.redirectErrorStream());
 assertEquals(ProcessBuilder.Redirect.PIPE, processBuilder.redirectError());
}

代码示例来源:origin: stackoverflow.com

ProcessBuilder builder = new ProcessBuilder("sh", "somescript.sh");
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("out.txt"));
Process p = builder.start(); // may throw IOException

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testCommandWrapperRedirectErrorInherit() {
 CommandWrapper commandWrapper = CommandWrapper.create();
 commandWrapper.setCommand(COMMAND);
 commandWrapper.setRedirectErrorInherit();
 ProcessBuilder processBuilder = commandWrapper.getBuilder();
 if (BaseEmulatorHelper.isWindows()) {
  assertEquals(WIN_COMMAND, processBuilder.command());
 } else {
  assertEquals(UNIX_COMMAND, processBuilder.command());
 }
 assertNull(processBuilder.directory());
 assertFalse(processBuilder.redirectErrorStream());
 assertEquals(ProcessBuilder.Redirect.INHERIT, processBuilder.redirectError());
}

代码示例来源:origin: apache/storm

private boolean isPosixProcessAlive(long pid, String user) throws IOException {
  boolean ret = false;
  ProcessBuilder pb = new ProcessBuilder("ps", "-o", "user", "-p", String.valueOf(pid));
  pb.redirectError(Redirect.INHERIT);
  Process p = pb.start();
  try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
    String first = in.readLine();
    assert ("USER".equals(first));
    String processUser;
    while ((processUser = in.readLine()) != null) {
      if (user.equals(processUser)) {
        ret = true;
        break;
      } else {
        LOG.info("Found {} running as {}, but expected it to be {}", pid, processUser, user);
      }
    }
  }
  return ret;
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testCommandWrapperRedirectErrorStream() {
 CommandWrapper commandWrapper = CommandWrapper.create();
 commandWrapper.setCommand(COMMAND);
 commandWrapper.setRedirectErrorStream();
 ProcessBuilder processBuilder = commandWrapper.getBuilder();
 if (BaseEmulatorHelper.isWindows()) {
  assertEquals(WIN_COMMAND, processBuilder.command());
 } else {
  assertEquals(UNIX_COMMAND, processBuilder.command());
 }
 assertNull(processBuilder.directory());
 assertTrue(processBuilder.redirectErrorStream());
 assertEquals(ProcessBuilder.Redirect.PIPE, processBuilder.redirectError());
}

代码示例来源:origin: jphp-group/jphp

@Signature
public WrapProcess redirectErrorToInherit() {
  processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
  return this;
}

代码示例来源:origin: jphp-group/jphp

@Signature
public WrapProcess redirectErrorToPipe() {
  processBuilder.redirectError(ProcessBuilder.Redirect.PIPE);
  return this;
}

代码示例来源:origin: jphp-group/jphp

@Signature
public WrapProcess redirectErrorToFile(File file) {
  processBuilder.redirectError(file);
  return this;
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Starts the process.
 */
public synchronized void start() throws IOException {
 Preconditions.checkState(mProcess == null, "Process is already running");
 String java = PathUtils.concatPath(System.getProperty("java.home"), "bin", "java");
 String classpath = System.getProperty("java.class.path");
 List<String> args = new ArrayList<>(Arrays.asList(java, "-cp", classpath));
 for (Entry<PropertyKey, String> entry : mConf.entrySet()) {
  args.add(String.format("-D%s=%s", entry.getKey().toString(), entry.getValue()));
 }
 args.add(mClazz.getCanonicalName());
 ProcessBuilder pb = new ProcessBuilder(args);
 pb.redirectError(mOutFile);
 pb.redirectOutput(mOutFile);
 mProcess = pb.start();
}

代码示例来源:origin: apache/storm

private boolean isWindowsProcessAlive(long pid, String user) throws IOException {
  boolean ret = false;
  ProcessBuilder pb = new ProcessBuilder("tasklist", "/fo", "list", "/fi", "pid eq " + pid, "/v");
  pb.redirectError(Redirect.INHERIT);
  Process p = pb.start();
  try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
    String read;
    while ((read = in.readLine()) != null) {
      if (read.contains("User Name:")) { //Check for : in case someone called their user "User Name"
        //This line contains the user name for the pid we're looking up
        //Example line: "User Name:    exampleDomain\exampleUser"
        List<String> userNameLineSplitOnWhitespace = Arrays.asList(read.split(":"));
        if (userNameLineSplitOnWhitespace.size() == 2) {
          List<String> userAndMaybeDomain = Arrays.asList(userNameLineSplitOnWhitespace.get(1).trim().split("\\\\"));
          String processUser = userAndMaybeDomain.size() == 2 ? userAndMaybeDomain.get(1) : userAndMaybeDomain.get(0);
          if (user.equals(processUser)) {
            ret = true;
          } else {
            LOG.info("Found {} running as {}, but expected it to be {}", pid, processUser, user);
          }
        } else {
          LOG.error("Received unexpected output from tasklist command. Expected one colon in user name line. Line was {}",
            read);
        }
        break;
      }
    }
  }
  return ret;
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Copies the work directory to the artifacts folder.
 */
public synchronized void saveWorkdir() throws IOException {
 Preconditions.checkState(mState == State.STARTED,
   "cluster must be started before you can save its work directory");
 ARTIFACTS_DIR.mkdirs();
 File tarball = new File(mWorkDir.getParentFile(), mWorkDir.getName() + ".tar.gz");
 // Tar up the work directory.
 ProcessBuilder pb =
   new ProcessBuilder("tar", "-czf", tarball.getName(), mWorkDir.getName());
 pb.directory(mWorkDir.getParentFile());
 pb.redirectOutput(Redirect.appendTo(TESTS_LOG));
 pb.redirectError(Redirect.appendTo(TESTS_LOG));
 Process p = pb.start();
 try {
  p.waitFor();
 } catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  throw new RuntimeException(e);
 }
 // Move tarball to artifacts directory.
 File finalTarball = new File(ARTIFACTS_DIR, tarball.getName());
 FileUtils.moveFile(tarball, finalTarball);
 LOG.info("Saved cluster {} to {}", mClusterName, finalTarball.getAbsolutePath());
}

代码示例来源:origin: eclipse-vertx/vert.x

private void executeUserCommand(Handler<Void> onCompletion) {
 if (cmd != null) {
  try {
   List<String> command = new ArrayList<>();
   if (ExecUtils.isWindows()) {
    ExecUtils.addArgument(command, "cmd");
    ExecUtils.addArgument(command, "/c");
   } else {
    ExecUtils.addArgument(command, "sh");
    ExecUtils.addArgument(command, "-c");
   }
   // Do not add quote to the given command:
   command.add(cmd);
   final Process process = new ProcessBuilder(command)
     .redirectError(ProcessBuilder.Redirect.INHERIT)
     .redirectOutput(ProcessBuilder.Redirect.INHERIT)
     .start();
   int status = process.waitFor();
   LOGGER.info("User command terminated with status " + status);
  } catch (Throwable e) {
   LOGGER.error("Error while executing the on-redeploy command : '" + cmd + "'", e);
  }
 }
 onCompletion.handle(null);
}

代码示例来源:origin: neo4j/neo4j

private static Process start( boolean inheritOutput, String... args )
{
  ProcessBuilder builder = new ProcessBuilder( args );
  if ( inheritOutput )
  {
    // We can not simply use builder.inheritIO here because
    // that will also inherit input which will be closed in case of background execution of main process.
    // Closed input stream will cause immediate exit from a subprocess liveloop.
    // And we use background execution in scripts and on CI server.
    builder.redirectError( ProcessBuilder.Redirect.INHERIT )
        .redirectOutput( ProcessBuilder.Redirect.INHERIT );
  }
  try
  {
    return builder.start();
  }
  catch ( IOException e )
  {
    throw new RuntimeException( "Failed to start sub process", e );
  }
}

代码示例来源:origin: apache/incubator-pinot

private void runAdminCommand(String... args)
   throws Exception {
  ArrayList<String> commandLine = Lists
    .newArrayList("java", "-cp", "pinot-tools/target/pinot-tool-launcher-jar-with-dependencies.jar",
      "org.apache.pinot.tools.admin.PinotAdministrator");

  commandLine.addAll(Lists.newArrayList(args));

  LOGGER.info("Running command " + Joiner.on(" ").join(commandLine));

  Process process =
    new ProcessBuilder(commandLine.toArray(new String[0])).redirectOutput(ProcessBuilder.Redirect.INHERIT)
      .redirectError(ProcessBuilder.Redirect.INHERIT).start();
  int returnCode = process.waitFor();
  assertEquals(returnCode, 0);
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

builder.command(cmd);
if (redirect) {
 builder.redirectError(ProcessBuilder.Redirect.INHERIT);
 builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

代码示例来源:origin: ehcache/ehcache3

private static void installKit(String diskPrefix) {
 try {
  Process process = new ProcessBuilder(diskPrefix + "../../gradlew", "copyServerLibs")
   .redirectError(ProcessBuilder.Redirect.INHERIT)
   .redirectOutput(ProcessBuilder.Redirect.INHERIT)
   .start();
  int status = process.waitFor();
  assertThat(status).isZero();
 } catch (IOException e) {
  fail("Failed to start gradle to install kit", e);
 } catch (InterruptedException e) {
  fail("Interrupted while installing kit", e);
 }
}

相关文章