001/* 002 * SonarQube, open source software quality management tool. 003 * Copyright (C) 2008-2014 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * SonarQube is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * SonarQube 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 Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.process; 021 022import org.apache.commons.io.IOUtils; 023import org.slf4j.LoggerFactory; 024 025import javax.annotation.Nullable; 026 027public class ProcessUtils { 028 029 private ProcessUtils() { 030 // only static stuff 031 } 032 033 /** 034 * Do not abuse to this method. It uses exceptions to get status. 035 * @return false if process is null or terminated, else true. 036 */ 037 public static boolean isAlive(@Nullable Process process) { 038 boolean alive = false; 039 if (process != null) { 040 try { 041 process.exitValue(); 042 } catch (IllegalThreadStateException ignored) { 043 alive = true; 044 } 045 } 046 return alive; 047 } 048 049 /** 050 * Send kill signal to stop process. Shutdown hooks are executed. It's the equivalent of SIGTERM on Linux. 051 * Correctly tested on Java 6 and 7 on both Mac/MSWindows 052 * @return true if the signal is sent, false if process is already down 053 */ 054 public static boolean sendKillSignal(@Nullable Process process) { 055 boolean sentSignal = false; 056 if (isAlive(process)) { 057 try { 058 process.destroy(); 059 sentSignal = true; 060 } catch (Exception e) { 061 LoggerFactory.getLogger(ProcessUtils.class).error("Fail to kill " + process, e); 062 } 063 } 064 return sentSignal; 065 } 066 067 public static void closeStreams(@Nullable Process process) { 068 if (process!=null) { 069 IOUtils.closeQuietly(process.getInputStream()); 070 IOUtils.closeQuietly(process.getOutputStream()); 071 IOUtils.closeQuietly(process.getErrorStream()); 072 } 073 } 074}