Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a process start by ProcessBuilder in java

Tags:

java

scala

I start processes with ProcessBuilder in Java. Multiple process may be started. How do I stop a Process?

public void terminalExecute(String builder) throws InterruptedException
{
    System.out.println(builder);
    String[] splits = builder.split(" ");
    System.out.println(splits.length);

    ProcessBuilder pb = new ProcessBuilder(splits[0],splits[1],splits[2],splits[3],splits[4],splits[5],splits[6],splits[7]);
    Process p = null ;
    pb.redirectErrorStream(true); 
    try {
        p = pb.start();

        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s = "";
        while((s = in.readLine()) != null){
            System.out.println(s);
        }
        int status = p.waitFor();
        System.out.println("Exited with status: " + status);
    } catch (IOException e) {
        e.printStackTrace();
    }

   
}

In another class I called this function like :

 String cmd ="java -Xmx3024m -XX:MaxPermSize=512m -Xms1024m -cp "+ ConfReader.getAFFJarPath()+" core.StrWorkflow "+new BigInteger(serviceRequest.getBytes());
 ProcessExecutor procExec = new ProcessExecutor();
 procExec.terminalExecute(cmd);

How I get the process id in this class ?

like image 632
AkhilaV Avatar asked Jan 02 '16 10:01

AkhilaV


1 Answers

start() method of ProcessBuilder returns a Process instance. You can call destroy() method on it.

See: https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html

like image 116
Prim Avatar answered Oct 30 '22 11:10

Prim