2

Possible Duplicate:
Knowing which java.exe process to kill on a windows machine
How to kill a process in Java, given a specific PID

I am trying to find out how to close a particular external exe namely cwserv5.exe. I have succeeded in starting a new external exe and closing it .But not an existing process. Can you help? Below is what I was tinkering with but really lost to be honest

package com.TestCase;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ReStartEXE {

    static Process pr; 

    public static void open() {

        //ProcessBuilder

         try {
             Runtime rt = Runtime.getRuntime();
             //Process pr = rt.exec("cmd /c dir");
              pr = rt.exec("C:\\APPLEGREEN\\webserv\\cwserv5rost.exe");         

             Thread.sleep(10000);
             //pr.wait(10000);
            //pr.waitFor();

             BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            // String line=null;

             /*while((line=input.readLine()) != null) {
                 System.out.println(line);
             }*/

             //int exitVal = pr.waitFor();
             //pr.destroy();
           // Process.kill(pr);
            // Runtime.getRuntime().exec("taskkill /F /IM cwserv5rost.exe");

             //System.out.println("Exited with error code "+exitVal);

         } catch(Exception e) {
             System.out.println(e.toString());
             e.printStackTrace();
         }
     }


    public static void Close() {

        pr.destroy();

    }

}
Community
  • 1
  • 1
user947265
  • 31
  • 1
  • 2
  • 5

2 Answers2

7

You can do this by executing a process to close the process that you want to close.

In your comments I can see taskkill, which means that you're probably using Windows.

Runtime rt = Runtime.getRuntime();

rt.exec("taskkill /F /IM cwserv5.exe");

This will force the process with image name cwserv5.exe to end.

If you don't want to force it to end, don't use the /f tag.

For more information on taskkill, go to cmd (command prompt) and type taskkill /?.

eboix
  • 4,853
  • 1
  • 24
  • 37
1

try this,

    Process proc = rt.exec("taskkill /F /IM cwserv5.exe");
    BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    while ((line = input.readLine()) != null){
         //do something
     }
    input.close();
    code = proc.exitValue();
    if(code==0){
        //success
    }
    else{
        //failure
    }
Ankur
  • 11,601
  • 5
  • 32
  • 66