Path: blob/master/test/hotspot/jtreg/serviceability/tmtools/share/common/ToolRunner.java
41159 views
/*1* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/22package common;2324import java.nio.file.Files;25import java.nio.file.Path;26import java.nio.file.Paths;27import java.util.Arrays;28import java.time.Instant;2930/**31* This class starts a process specified by the passed command line waits till32* the process completes and returns the process exit code and stdout and stderr33* output as ToolResults34*/35class ToolRunner {36private final String[] cmdArgs;3738ToolRunner(String cmdLine) {39cmdArgs = cmdLine.split(" +");40}4142/**43* Starts the process, waits for the process completion and returns the44* results45*46* @return process results47* @throws Exception if anything goes wrong48*/49ToolResults runToCompletion() throws Exception {50ProcessBuilder pb = new ProcessBuilder(cmdArgs);51Path out = Files.createTempFile(Paths.get("."), "out.", ".txt");52Path err = out.resolveSibling(out.getFileName().toString().replaceFirst("out", "err"));5354Process p = pb.redirectOutput(ProcessBuilder.Redirect.to(out.toFile()))55.redirectError(ProcessBuilder.Redirect.to(err.toFile()))56.start();57System.out.printf("[%s] started process %d %s with out/err redirected to '%s' and '%s'%n",58Instant.now().toString(), p.pid(), pb.command(), out.toString(), err.toString());59int exitCode = p.waitFor();60System.out.printf("[%s] process %d finished with exit code = %d%n",61Instant.now().toString(), p.pid(), exitCode);62return new ToolResults(exitCode, Files.readAllLines(out), Files.readAllLines(err));63}64}656667