/******************************************************************************* * ALMA - Atacama Large Millimeter Array * Copyright (c) ESO - European Southern Observatory, 2011 * (in the framework of the ALMA collaboration). * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************************/ package alma.acs.testsupport; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import alma.acs.concurrent.DaemonThreadFactory; import alma.acs.util.ProcessStreamGobbler; /** * Helper class to be used by tests which need to verify that some other process exists * or does not exist, or that need to kill some process. * Don't use this class in operational code! */ public class ProcessUtil { private final Logger logger; private volatile boolean DEBUG = false; public ProcessUtil(Logger logger) { this.logger = logger; } /** * Gets the process IDs of all java processes run by the current user on the local host, * whose main class is given as the parameter. *
* The "jps" command is used via Runtime.exec, which should work not only on Linux
* but also on Windows.
*
* @throws IOException
*/
public List
* @TODO Currently this method works only on Linux because it uses the "kill -9" command.
*
* @TODO Currently the stdout and stderr from running "kill" are not gobbled because
* they are expected to be very small and thus won't block buffers etc.
* If they do, then use {@link ProcessStreamGobbler} also here.
*
* @param tough if true, a tough way of killing is used (kill -9)
* @return Exit value of the kill command
* @throws IOException
* @throws InterruptedException
*/
public int killProcess(String pid, boolean tough) throws IOException, InterruptedException {
String command = "kill ";
if (tough) {
command += "-9 ";
}
command += pid;
logger.info("Will kill process " + pid + " using command '" + command + "'.");
Process killProc = Runtime.getRuntime().exec(command);
return killProc.waitFor();
}
/**
* Gets a map with key=(running java main classes) and value=(list of the process IDs).
* Filters out sun.tools.jps.Jps which is the tool used to get the processes.
* @return Map