Example usage for java.lang Process destroy

List of usage examples for java.lang Process destroy

Introduction

In this page you can find the example usage for java.lang Process destroy.

Prototype

public abstract void destroy();

Source Link

Document

Kills the process.

Usage

From source file:com.clustercontrol.ping.util.ReachAddressFping.java

/**
 * ????????????/*  ww w  .j  a v a2s.c o  m*/
 * 
 * @param info
 * @return PING
 */
public boolean isReachable(HashSet<String> hosts, int version) {

    Process process = null;//fping
    int m_exitValue = 0; //fping?

    String fpingPath;
    if (version == 6) {
        fpingPath = PingProperties.getFping6Path();
    } else {
        fpingPath = PingProperties.getFpingPath();
    }
    String cmd[] = FpingCommand.getCommand(fpingPath, hosts, m_sentCount, m_sentInterval, m_timeout, m_bytes);

    try {
        process = Runtime.getRuntime().exec(cmd);

        if (process != null) {
            //???
            StreamReader errStreamReader = new StreamReader(process.getErrorStream());
            errStreamReader.start();
            StreamReader inStreamReader = new StreamReader(process.getInputStream());
            inStreamReader.start();

            //            
            m_exitValue = process.waitFor();

            //?

            inStreamReader.join();
            m_resultMsg = inStreamReader.getResult();
            m_log.debug("isReachable() STDOUT :" + inStreamReader.getResult().toString());

            errStreamReader.join();
            m_errMsg = errStreamReader.getResult();
            m_log.debug("isReachable() STDERR :" + errStreamReader.getResult().toString());

        }
    } catch (IOException e) {
        m_errMsg = new ArrayList<String>();
        m_errMsg.add(e.getMessage());
        m_log.warn("isReachable() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        return false;

    } catch (InterruptedException e) {
        m_errMsg = new ArrayList<String>();
        m_errMsg.add(e.getMessage());
        m_log.warn("isReachable() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        return false;
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    if (m_exitValue == 0 || m_exitValue == 1) {
        m_log.debug("exit value = " + m_exitValue);

        //fping??0????
        //fping??unreachable??1??????1???
        return true;
    } else {
        String errMsg = "fping exit value is not 0 or 1. exit value = " + m_exitValue;
        m_log.info(errMsg);
        for (int j = 0; j < cmd.length; j++) {
            m_log.info("cmd[" + j + "] = " + cmd[j]);
        }

        m_errMsg = new ArrayList<String>();
        m_errMsg.add(errMsg);

        //fping??!0 or !1???
        return false;
    }
}

From source file:com.clustercontrol.agent.job.DeleteProcessThread.java

/**
 * ?<BR>/* w  ww  . j a v a 2s.  co m*/
 * 
 * ReceiveTopic??????????? ??????
 * 
 */
/*
 * (non-Javadoc)
 * 
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    m_log.debug("run start");

    Process process = null;

    //??
    process = RunHistoryUtil.findRunHistory(m_info);

    if (process == null) {
        // ????????
        m_log.warn("run() : process is null");
        RunResultInfo info = new RunResultInfo();
        info.setSessionId(m_info.getSessionId());
        info.setJobunitId(m_info.getJobunitId());
        info.setJobId(m_info.getJobId());
        info.setFacilityId(m_info.getFacilityId());
        info.setCommand(m_info.getCommand());
        info.setCommandType(m_info.getCommandType());
        info.setStopType(m_info.getStopType());
        info.setStatus(RunStatusConstant.ERROR);
        info.setTime(HinemosTime.getDateInstance().getTime());
        info.setEndValue(-1);
        info.setMessage("Internal Error : Ex. Agent restarted or Job already terminated.");
        info.setErrorMessage("");
        // ?
        m_sendQueue.put(info);
        return;
    }

    // ---------------------------
    // -- ?
    // ---------------------------

    // ?
    RunResultInfo info = new RunResultInfo();
    info.setSessionId(m_info.getSessionId());
    info.setJobunitId(m_info.getJobunitId());
    info.setJobId(m_info.getJobId());
    info.setFacilityId(m_info.getFacilityId());
    info.setCommand(m_info.getCommand());
    info.setCommandType(m_info.getCommandType());
    info.setStopType(m_info.getStopType());
    info.setStatus(RunStatusConstant.START);
    info.setTime(HinemosTime.getDateInstance().getTime());

    m_log.info("Process Delete SessionID=" + m_info.getSessionId() + ", JobID=" + m_info.getJobId());

    // ?
    m_sendQueue.put(info);

    //??
    m_log.info("run() : shutdown process : " + process.toString());
    try {
        process.destroy();
        info.setEndValue(process.waitFor());
    } catch (Exception e) {
        m_log.warn("shutdown process : " + e.getMessage());

        // ?
        info.setTime(HinemosTime.getDateInstance().getTime());
        info.setEndValue(-1);
        info.setStatus(RunStatusConstant.ERROR);
        info.setMessage(e.getMessage());
        info.setErrorMessage("");
        m_sendQueue.put(info);
        return;
    }

    // ---------------------------
    // -- ?
    // ---------------------------

    info.setTime(HinemosTime.getDateInstance().getTime());
    info.setStatus(RunStatusConstant.END);
    m_sendQueue.put(info);

    ////?
    RunHistoryUtil.delRunHistory(m_info);

    m_log.debug("run end");
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java

/**
 * Returns when the process has exited without errors. This will wait for
 * the process to exist, therefore will block the current thread in which it
 * is running. If any errors occur, throws CoreException CoreException
 * @throws CoreException if any errors occur while the process is being
 * launched//w ww .  j  a v  a  2s . c om
 */
public void run() throws CoreException {
    Exception error = null;
    Process p = null;
    try {

        List<String> processArguments = getProcessArguments();

        if (processArguments == null || processArguments.isEmpty()) {
            throw new CoreException(getErrorStatus("No process arguments were found")); //$NON-NLS-1$
        } else {

            ProcessBuilder processBuilder = new ProcessBuilder(processArguments);

            // Set any environment variables
            Map<String, String> envVars = getEnvironmentVariables();
            if (envVars != null) {
                Map<String, String> actualVars = processBuilder.environment();
                if (actualVars != null) {
                    for (Entry<String, String> entry : envVars.entrySet()) {
                        actualVars.put(entry.getKey(), entry.getValue());
                    }
                }
            }

            p = processBuilder.start();

            if (p == null) {
                throw new CoreException(getErrorStatus("No process was created.")); //$NON-NLS-1$
            } else {

                StringBuffer errorBuffer = new StringBuffer();
                // Clear the input and error streams to prevent the
                // process
                // from blocking
                handleProcessIOAsynch(p, null, errorBuffer);

                p.waitFor();

                if (errorBuffer.length() > 0) {
                    throw new CoreException(getErrorStatus(errorBuffer.toString()));
                } else if (p.exitValue() != 0) {
                    throw new CoreException(getErrorStatus("process exit value: " + p.exitValue())); //$NON-NLS-1$
                }
            }
        }
    } catch (InterruptedException ex) {
        error = ex;
    } catch (IOException ioe) {
        error = ioe;
    } catch (SecurityException se) {
        error = se;
    } finally {
        if (p != null) {
            p.destroy();
        }
    }

    if (error != null) {
        throw error instanceof CoreException ? (CoreException) error : CloudErrorUtil.toCoreException(error);
    }

}

From source file:hobby.wei.c.phone.Network.java

public static String PING(String host, boolean format) {
    final int PACKAGES = 4;
    String info = null;/*from  w w  w . ja  v a  2 s . c o  m*/
    String print = null;
    Process process = null;
    LineNumberReader reader = null;
    try {
        final String CMD = "ping -c " + PACKAGES + " " + host;
        if (format) {
            info = "ping-c" + PACKAGES + "-" + host.replace('.', '_');
        } else {
            print = CMD + "\n";
        }

        process = Runtime.getRuntime().exec(CMD);
        reader = new LineNumberReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        boolean start = false;
        int index = -1;
        while ((line = reader.readLine()) != null) {
            if (!format) {
                print += line + "\n";
            } else {
                line = line.trim();
                if (line.toLowerCase().startsWith("ping")) {
                    line = line.substring(0, line.indexOf(')'));
                    line = line.replace("(", "");
                    line = line.replace(' ', '-');
                    line = line.replace('.', '_');
                    start = true;
                } else if (start) {
                    index = line.indexOf(':');
                    if (index > 0) {
                        //?ttl=53
                        line = line.substring(index + 1).trim();
                        index = line.indexOf(' ');
                        line = line.substring(index + 1, line.indexOf(' ', index + 3)).trim();
                        line = line.replace('=', '_');
                        start = false;
                    } else {
                        start = false;
                        continue;
                    }
                } else if (line.startsWith("" + PACKAGES)) {
                    index = line.indexOf(',');
                    line = line.substring(index + 1).trim();
                    line = line.substring(0, line.indexOf(' ')).trim();
                    line = line + "in" + PACKAGES + "received";
                } else if (line.startsWith("rtt")) {
                    line = line.replaceFirst(" ", "-");
                    line = line.replace(" ", "");
                    line = line.replace('/', '-');
                    line = line.replace('.', '_');
                    line = line.replace("=", "--");
                } else {
                    continue;
                }
                if (info == null)
                    info = line;
                info += "--" + line;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (process != null)
                process.destroy(); //??
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
    return format ? info : print;
}

From source file:org.xmlsh.sh.shell.Shell.java

public void terminateChildProcesses() {
    if (mChildProcess == null)
        return;//  w w w .ja  v  a2 s . c  o m
    synchronized (mChildProcess) {
        for (Process p : mChildProcess)
            p.destroy();
        mChildProcess.clear();
    }
}

From source file:org.ow2.proactive.scheduler.task.executors.ForkedTaskExecutor.java

@Override
public TaskResultImpl execute(TaskContext context, PrintStream outputSink, PrintStream errorSink) {
    CookieBasedProcessTreeKiller taskProcessTreeKiller = null;
    Process process = null;
    ProcessStreamsReader processStreamsReader = null;
    File serializedContext = null;

    try {/*w w w. ja va2  s.com*/
        if (!workingDir.exists()) {
            FileUtils.forceMkdir(workingDir);
        }
        serializedContext = taskContextSerializer.serializeContext(context, workingDir);

        OSProcessBuilder processBuilder = forkedJvmProcessBuilderCreator.createForkedProcessBuilder(context,
                serializedContext, outputSink, errorSink, workingDir);

        TaskId taskId = context.getTaskId();

        String cookieNameSuffix = "Job" + taskId.getJobId().value() + "Task" + taskId.value();

        taskProcessTreeKiller = CookieBasedProcessTreeKiller.createProcessChildrenKiller(cookieNameSuffix,
                processBuilder.environment());

        process = processBuilder.start();
        processStreamsReader = new ProcessStreamsReader(taskId.toString(), process, outputSink, errorSink);

        int exitCode = process.waitFor();

        if (exitCode != 0) {
            try {
                Object error = deserializeTaskResult(serializedContext);
                if (error instanceof TaskContext) {
                    return createTaskResult(context,
                            new IOException("Forked JVM process returned with exit code " + exitCode
                                    + ", see task logs for more information"));
                } else {
                    Throwable exception = (Throwable) error;
                    return createTaskResult(context, exception);
                }
            } catch (Throwable cannotDeserializeResult) {
                return createTaskResult(context, cannotDeserializeResult);
            }
        }

        return (TaskResultImpl) deserializeTaskResult(serializedContext);
    } catch (Throwable throwable) {
        return createTaskResult(context, throwable);
    } finally {
        FileUtils.deleteQuietly(serializedContext);

        if (process != null) {
            process.destroy();
        }
        if (taskProcessTreeKiller != null) {
            taskProcessTreeKiller.kill();
        }
        if (processStreamsReader != null) {
            processStreamsReader.close();
        }
    }
}

From source file:org.wso2.carbon.integration.tests.carbontools.RunBuildXMLTestCase.java

@Test(groups = { "carbon.core" }, description = "Running the ant command and verifying the jar copying")
public void testBuildXMLGenerateRemoteRegistryClients() throws Exception {
    boolean isJarCreated = false;
    Process process = null;
    try {/*from   ww  w  .  j ava  2 s  .c  o  m*/

        File folder = new File(carbonHome + File.separator + "repository" + File.separator + "lib");
        File[] listOfFilesBeforeRunAntCommand = folder.listFiles(new FilenameFilter() {
            public boolean accept(File directory, String fileName) {
                return fileName.toLowerCase().endsWith(".jar");
            }
        });
        String[] cmdArray;

        if ((CarbonCommandToolsUtil.getCurrentOperatingSystem()
                .contains(OperatingSystems.WINDOWS.name().toLowerCase()))) {
            cmdArray = new String[] { "cmd.exe", "/c", "start", "ant" };//run ant comment in bin directory
        } else {
            cmdArray = new String[] { "ant" };
        }

        process = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArray);
        long startTime = System.currentTimeMillis();

        while ((System.currentTimeMillis() - startTime) < CarbonIntegrationConstants.DEFAULT_WAIT_MS) {
            File[] listOfFilesAfterRunAntCommand = folder.listFiles(new FilenameFilter() {
                public boolean accept(File directory, String fileName) {
                    return fileName.toLowerCase().endsWith(".jar");
                }
            });

            if (listOfFilesBeforeRunAntCommand != null && listOfFilesAfterRunAntCommand != null) {
                if (listOfFilesAfterRunAntCommand.length > listOfFilesBeforeRunAntCommand.length) {
                    log.info("Jars copied successfully");
                    isJarCreated = true;
                    break;
                }
            } else if (listOfFilesAfterRunAntCommand != null && listOfFilesAfterRunAntCommand.length > 0) {
                log.info("Jars copied successfully");
                isJarCreated = true;
                break;
            } else {
                Thread.sleep(1000); // Sleeping 1 second
            }

        }
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    assertTrue(isJarCreated, "Jar not copied successfully");
}

From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java

/**
 * Runs a command specified by a compiler invocation.
 *
 * @param compilerInvocation/*from   www . j  a  v  a 2  s .c  o  m*/
 *            specifies what program with which flags is being executed
 * @param pathToSourceFolder
 *            the path to the source folder of the submission
 * @return CompilerOutput with fields initialized according to the outcome
 *         of the process
 * @throws BadFlagException
 *             if a flag is not known to javac
 */
private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit)
        throws BadFlagException {
    Process compilerProcess = null;
    try {
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) {
            compilerProcessBuilder.directory(pathToSourceFolder.toFile());
        } else {
            compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // which is
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok javac reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if javac should unexpectedly
        // terminate
        LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: "
                + pathToSourceFolder.toString() + " Got message: " + e.getMessage());
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    splitCompilerOutput(compilerOutputLines, compilerOutput);

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    return compilerOutput;
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

@Override
public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    // First we build the command to invoke the compiler. This consists of
    // the compiler executable, the path of the
    // file to compile and compiler flags. So for example we call:
    List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags);
    // Now we build a launchable process from the given parameters and set
    // the working directory.
    Process compilerProcess = null;

    try {/*from  w  ww  . j av a2 s.  c  o  m*/
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToProgramFile)) {
            compilerProcessBuilder.directory(pathToProgramFile.toFile());
        } else {
            compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH");
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok gcc reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if gcc should unexpectedly terminate
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);

    // delete all .o and .exe files
    // these are output files generated by gcc which we won't need
    // anymore
    File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles();
    for (File candidateFile : candidateToplevelFiles) {
        if (!candidateFile.isDirectory()) {
            String extension = FilenameUtils.getExtension(candidateFile.toString());
            if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) {
                // We only pass the filename, since gcc will be
                // confined to the dir the file is located in.
                candidateFile.delete();
            }
        }

    }

    return compilerOutput;
}

From source file:org.drools.planner.examples.nurserostering.competition.NurseRosteringEvaluatorHelper.java

public void evaluate(String filePrefix, String fileSuffix, String lineContainsFilter) {
    Process process = null;
    try {//from   www  .j av a2 s  . co  m
        File inputFile = new File(solutionBusiness.getImportDataDir(), filePrefix + ".xml").getCanonicalFile();
        File solvedFile = new File(solutionBusiness.getSolvedDataDir(), filePrefix + fileSuffix + ".xml")
                .getCanonicalFile();
        if (!solvedFile.exists()) {
            logger.info("Skipping inputFile ({}) because no solvedFile found.", inputFile);
            return;
        }
        solutionBusiness.openSolution(solvedFile);
        HardAndSoftScore score = (HardAndSoftScore) solutionBusiness.getScore();
        File outputFile = new File(solutionBusiness.getExportDataDir(), filePrefix + fileSuffix + ".xml")
                .getCanonicalFile();
        solutionBusiness.exportSolution(outputFile);
        File evaluatorDir = new File("local/competition/nurserostering/");
        String command = "java -jar evaluator.jar " + inputFile.getAbsolutePath() + " "
                + outputFile.getAbsolutePath();
        process = Runtime.getRuntime().exec(command, null, evaluatorDir);
        EvaluatorSummaryFilterOutputStream out = new EvaluatorSummaryFilterOutputStream(outputFile.getName(),
                lineContainsFilter);
        IOUtils.copy(process.getInputStream(), out);
        IOUtils.copy(process.getErrorStream(), System.err);
        out.writeResults();
        int penaltyTotal = out.getPenaltyTotal();
        if (score.getHardScore() == 0) {
            if (score.getSoftScore() == (-penaltyTotal)) {
                System.out.println("The calculated soft score (" + score.getSoftScore()
                        + ") is the same as the evaluator penalty total (" + penaltyTotal + ").");
            } else {
                throw new IllegalStateException("The calculated soft score (" + score.getSoftScore()
                        + ") is not the same as the evaluator penalty total (" + penaltyTotal + ").");
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}