Руководство по API java.lang.ProcessBuilder

1. Обзор

Process API предоставляет мощный способ выполнения команд операционной системы на Java. Однако у него есть несколько вариантов, которые могут затруднить работу.

В этом руководстве мы рассмотрим, как Java решает эту проблему с помощью ProcessBuilder API.

2. API ProcessBuilder

Класс ProcessBuilder предоставляет методы для создания и настройки процессов операционной системы. Каждый экземпляр ProcessBuilder позволяет нам управлять набором атрибутов процесса . Затем мы можем запустить новый процесс с этими атрибутами.

Вот несколько распространенных сценариев, в которых мы могли бы использовать этот API:

  • Найдите текущую версию Java
  • Настройте специальную карту "ключ-значение" для нашей среды
  • Измените рабочий каталог, в котором выполняется наша команда оболочки
  • Перенаправить потоки ввода и вывода на пользовательские замены
  • Наследовать оба потока текущего процесса JVM
  • Выполнить команду оболочки из кода Java

Мы рассмотрим практические примеры каждого из них в следующих разделах.

Но прежде чем мы погрузимся в рабочий код, давайте посмотрим, какие функции предоставляет этот API.

2.1. Резюме метода

В этом разделе мы сделаем шаг назад и кратко рассмотрим наиболее важные методы класса ProcessBuilder . Это поможет нам, когда мы позже погрузимся в некоторые реальные примеры:

  • ProcessBuilder(String... command)

    Чтобы создать новый построитель процесса с указанной программой операционной системы и аргументами, мы можем использовать этот удобный конструктор.

  • directory(File directory)

    Мы можем переопределить рабочий каталог по умолчанию текущего процесса, вызвав метод каталога и передав объект File . По умолчанию для текущего рабочего каталога установлено значение, возвращаемое системным свойством user.dir .

  • environment()

    Если мы хотим получить текущие переменные среды, мы можем просто вызвать метод среды . Он возвращает нам копию текущей среды процесса, используя System.getenv (), но как карту .

  • inheritIO()

    Если мы хотим указать, что источник и место назначения для стандартного ввода-вывода нашего подпроцесса должны быть такими же, как у текущего процесса Java, мы можем использовать метод inheritIO .

  • redirectInput(File file), redirectOutput(File file), redirectError(File file)

    Когда мы хотим перенаправить стандартный ввод, вывод и место назначения ошибок построителя процессов в файл, в нашем распоряжении есть три подобных метода перенаправления.

  • start()

    И последнее, но не менее важное: чтобы начать новый процесс с тем, что мы настроили, мы просто вызываем start () .

Следует отметить, что этот класс НЕ синхронизирован . Например, если у нас есть несколько потоков, одновременно обращающихся к экземпляру ProcessBuilder, то синхронизацией необходимо управлять извне.

3. Примеры

Теперь, когда у нас есть базовые представления об API ProcessBuilder , давайте рассмотрим несколько примеров.

3.1. Использование ProcessBuilder для печати версии Java

В этом первом примере мы запустим команду java с одним аргументом, чтобы получить версию .

Process process = new ProcessBuilder("java", "-version").start();

Сначала мы создаем объект ProcessBuilder, передавая конструктору значения команды и аргумента. Затем мы запускаем процесс, используя метод start (), чтобы получить объект Process .

Теперь посмотрим, как обрабатывать вывод:

List results = readOutput(process.getInputStream()); assertThat("Results should not be empty", results, is(not(empty()))); assertThat("Results should contain java version: ", results, hasItem(containsString("java version"))); int exitCode = process.waitFor(); assertEquals("No errors should be detected", 0, exitCode);

Здесь мы читаем вывод процесса и проверяем, соответствует ли содержимое ожидаемому. На последнем этапе мы ждем завершения процесса с помощью process.waitFor () .

После завершения процесса возвращаемое значение сообщает нам, был ли процесс успешным или нет .

Следует иметь в виду несколько важных моментов:

  • Аргументы должны быть в правильном порядке
  • Кроме того, в этом примере используются рабочий каталог и среда по умолчанию.
  • Мы намеренно не вызываем process.waitFor () до тех пор, пока не прочитаем вывод, потому что буфер вывода может остановить процесс.
  • Мы сделали предположение, что команда java доступна через переменную PATH

3.2. Запуск процесса в измененной среде

В следующем примере мы увидим, как изменить рабочую среду.

Но прежде чем мы это сделаем, давайте начнем с того, что посмотрим, какую информацию мы можем найти в среде по умолчанию :

ProcessBuilder processBuilder = new ProcessBuilder(); Map environment = processBuilder.environment(); environment.forEach((key, value) -> System.out.println(key + value));

Это просто распечатает каждую из записей переменных, которые предоставляются по умолчанию:

PATH/usr/bin:/bin:/usr/sbin:/sbin SHELL/bin/bash ...

Now we're going to add a new environment variable to our ProcessBuilder object and run a command to output its value:

environment.put("GREETING", "Hola Mundo"); processBuilder.command("/bin/bash", "-c", "echo $GREETING"); Process process = processBuilder.start();

Let’s decompose the steps to understand what we've done:

  • Add a variable called ‘GREETING' with a value of ‘Hola Mundo' to our environment which is a standard Map
  • This time, rather than using the constructor we set the command and arguments via the command(String… command) method directly.
  • We then start our process as per the previous example.

To complete the example, we verify the output contains our greeting:

List results = readOutput(process.getInputStream()); assertThat("Results should not be empty", results, is(not(empty()))); assertThat("Results should contain java version: ", results, hasItem(containsString("Hola Mundo")));

3.3. Starting a Process With a Modified Working Directory

Sometimes it can be useful to change the working directory. In our next example we're going to see how to do just that:

@Test public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls"); processBuilder.directory(new File("src")); Process process = processBuilder.start(); List results = readOutput(process.getInputStream()); assertThat("Results should not be empty", results, is(not(empty()))); assertThat("Results should contain directory listing: ", results, contains("main", "test")); int exitCode = process.waitFor(); assertEquals("No errors should be detected", 0, exitCode); }

In the above example, we set the working directory to the project's src dir using the convenience method directory(File directory). We then run a simple directory listing command and check that the output contains the subdirectories main and test.

3.4. Redirecting Standard Input and Output

In the real world, we will probably want to capture the results of our running processes inside a log file for further analysis. Luckily the ProcessBuilder API has built-in support for exactly this as we will see in this example.

By default, our process reads input from a pipe. We can access this pipe via the output stream returned by Process.getOutputStream().

However, as we'll see shortly, the standard output may be redirected to another source such as a file using the method redirectOutput. In this case, getOutputStream() will return a ProcessBuilder.NullOutputStream.

Let's return to our original example to print out the version of Java. But this time let's redirect the output to a log file instead of the standard output pipe:

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); processBuilder.redirectErrorStream(true); File log = folder.newFile("java-version.log"); processBuilder.redirectOutput(log); Process process = processBuilder.start();

In the above example, we create a new temporary file called log and tell our ProcessBuilder to redirect output to this file destination.

In this last snippet, we simply check that getInputStream() is indeed null and that the contents of our file are as expected:

assertEquals("If redirected, should be -1 ", -1, process.getInputStream().read()); List lines = Files.lines(log.toPath()).collect(Collectors.toList()); assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));

Now let's take a look at a slight variation on this example. For example when we wish to append to a log file rather than create a new one each time:

File log = tempFolder.newFile("java-version-append.log"); processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(Redirect.appendTo(log));

It's also important to mention the call to redirectErrorStream(true). In case of any errors, the error output will be merged into the normal process output file.

We can, of course, specify individual files for the standard output and the standard error output:

File outputLog = tempFolder.newFile("standard-output.log"); File errorLog = tempFolder.newFile("error.log"); processBuilder.redirectOutput(Redirect.appendTo(outputLog)); processBuilder.redirectError(Redirect.appendTo(errorLog));

3.5. Inheriting the I/O of the Current Process

In this penultimate example, we'll see the inheritIO() method in action. We can use this method when we want to redirect the sub-process I/O to the standard I/O of the current process:

@Test public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello"); processBuilder.inheritIO(); Process process = processBuilder.start(); int exitCode = process.waitFor(); assertEquals("No errors should be detected", 0, exitCode); }

In the above example, by using the inheritIO() method we see the output of a simple command in the console in our IDE.

In the next section, we're going to take a look at what additions were made to the ProcessBuilder API in Java 9.

4. Java 9 Additions

Java 9 introduced the concept of pipelines to the ProcessBuilder API:

public static List startPipeline​(List builders) 

Using the startPipeline method we can pass a list of ProcessBuilder objects. This static method will then start a Process for each ProcessBuilder. Thus, creating a pipeline of processes which are linked by their standard output and standard input streams.

For example, if we want to run something like this:

find . -name *.java -type f | wc -l

What we'd do is create a process builder for each isolated command and compose them into a pipeline:

@Test public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { List builders = Arrays.asList( new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), new ProcessBuilder("wc", "-l")); List processes = ProcessBuilder.startPipeline(builders); Process last = processes.get(processes.size() - 1); List output = readOutput(last.getInputStream()); assertThat("Results should not be empty", output, is(not(empty()))); }

In this example, we're searching for all the java files inside the src directory and piping the results into another process to count them.

To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements.

5. Conclusion

To summarize, in this tutorial, we’ve explored the java.lang.ProcessBuilder API in detail.

First, we started by explaining what can be done with the API and summarized the most important methods.

Next, we took a look at a number of practical examples. Finally, we looked at what new additions were introduced to the API in Java 9.

Как всегда, полный исходный код статьи доступен на GitHub.