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 java.io.IOException; 023import java.util.List; 024import java.util.regex.Matcher; 025import java.util.regex.Pattern; 026 027import org.apache.commons.io.IOUtils; 028 029/** 030 * {@link ProcessManager} implementation for *nix systems. Uses the <tt>ps</tt> and <tt>kill</tt> commands. 031 * <p> 032 * Works for Linux. Works for Solaris too, except that the command line string returned by <tt>ps</tt> there is limited 033 * to 80 characters and this affects {@link #findPid(String)}. 034 */ 035public class UnixProcessManager implements ProcessManager { 036 037 protected static final boolean PID_ENABLED = true; 038 039 private static final Pattern PS_OUTPUT_LINE = Pattern.compile("^\\s*(\\d+)\\s+(.*)$"); 040 041 protected String[] psCommand() { 042 return new String[] { "/bin/ps", "-e", "-o", "pid,args" }; 043 } 044 045 @Override 046 public String findPid(String regex) throws IOException { 047 Pattern commandPattern = Pattern.compile(regex); 048 for (String line : execute(psCommand())) { 049 Matcher lineMatcher = PS_OUTPUT_LINE.matcher(line); 050 if (lineMatcher.matches()) { 051 String command = lineMatcher.group(2); 052 Matcher commandMatcher = commandPattern.matcher(command); 053 if (commandMatcher.find()) { 054 return lineMatcher.group(1); 055 } 056 } 057 } 058 return null; 059 } 060 061 @Override 062 public void kill(Process process, String pid) throws IOException { 063 execute("/bin/kill", "-KILL", pid); 064 } 065 066 private List<String> execute(String... command) throws IOException { 067 Process process = new ProcessBuilder(command).start(); 068 List<String> lines = IOUtils.readLines(process.getInputStream()); 069 return lines; 070 } 071 072 @Override 073 public boolean canFindPid() { 074 return PID_ENABLED; 075 } 076 077}