001// 002// JODConverter - Java OpenDocument Converter 003// Copyright 2009 Art of Solving Ltd 004// Copyright 2004-2009 Mirko Nasato 005// 006// JODConverter is free software: you can redistribute it and/or 007// modify it under the terms of the GNU Lesser General Public License 008// as published by the Free Software Foundation, either version 3 of 009// the License, or (at your option) any later version. 010// 011// JODConverter is distributed in the hope that it will be useful, 012// but WITHOUT ANY WARRANTY; without even the implied warranty of 013// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014// Lesser General Public License for more details. 015// 016// You should have received a copy of the GNU Lesser General 017// Public License along with JODConverter. If not, see 018// <http://www.gnu.org/licenses/>. 019// 020package org.nuxeo.launcher.process; 021 022import static java.nio.charset.StandardCharsets.UTF_8; 023 024import java.io.IOException; 025import java.util.List; 026import java.util.regex.Matcher; 027import java.util.regex.Pattern; 028 029import org.apache.commons.io.IOUtils; 030 031/** 032 * {@link ProcessManager} implementation for *nix systems. Uses the <tt>ps</tt> and <tt>kill</tt> commands. 033 * <p> 034 * Works for Linux. Works for Solaris too, except that the command line string returned by <tt>ps</tt> there is limited 035 * to 80 characters and this affects {@link #findPid(String)}. 036 */ 037public class UnixProcessManager implements ProcessManager { 038 039 protected static final boolean PID_ENABLED = true; 040 041 private static final Pattern PS_OUTPUT_LINE = Pattern.compile("^\\s*(\\d+)\\s+(.*)$"); 042 043 protected String[] psCommand() { 044 return new String[] { "/bin/ps", "-e", "-o", "pid,args" }; 045 } 046 047 @Override 048 public String findPid(String regex) throws IOException { 049 Pattern commandPattern = Pattern.compile(regex); 050 for (String line : execute(psCommand())) { 051 Matcher lineMatcher = PS_OUTPUT_LINE.matcher(line); 052 if (lineMatcher.matches()) { 053 String command = lineMatcher.group(2); 054 Matcher commandMatcher = commandPattern.matcher(command); 055 if (commandMatcher.find()) { 056 return lineMatcher.group(1); 057 } 058 } 059 } 060 return null; 061 } 062 063 @Override 064 public void kill(Process process, String pid) throws IOException { 065 execute("/bin/kill", "-KILL", pid); 066 } 067 068 private List<String> execute(String... command) throws IOException { 069 Process process = new ProcessBuilder(command).start(); 070 return IOUtils.readLines(process.getInputStream(), UTF_8); 071 } 072 073 @Override 074 public boolean canFindPid() { 075 return PID_ENABLED; 076 } 077 078}