Reputation: 601
I have my application in Java which invokes a browser [IE or Firefox etc ] ..
Requirement is when my Java Application exits i have to kill all the web pages [Child processes ] i have opened from my Application in IE/Firefox etc..
I use the following code .
Note : cmd contains "System Browser exe path and URL"
static ArrayList<Process> pro = new ArrayList<Process>();
String cmd=" ";
Process p = Runtime.getRuntime().exec(cmd);
pro.add(p);
I maintain a static arraylist to add all the process objects .
To kill the process i invoked i use the below code
Iterator<Process> iter = pro.iterator();
while(iter.hasNext()){
Process p = iter.next();
System.out.println("Now Killing "+p.toString());
p.destroy();
}
This code[p.destroy();] is working fine for Internet Explorer , But its not working for Firefox/Chrome...
Since Firefox runs as a Main process and the process what i invoke goes as its child :(...
I have to use generic fix for Windows and Linux..
I can even go for C++ file fix which does this with some search criteria ..so that i can execute that executable from my code using
Runtime.getRuntime().exec("executable cmd");
Upvotes: 3
Views: 3497
Reputation: 6003
In windows, you can run :
wmic process get description, executablepath, processid | findstr firefox
which will give you the PID of the firefox process. Then you can use tskill PID
to kill
the process.
Upvotes: 1
Reputation: 2942
try using pkill (killing by process name) command.
Runtime.getRuntime().exec("pkill firefox");
or in c++
system("pkill firefox");
But it's not platform independent. It will run on Unix-like operating system, and not in windows.
Upvotes: 0
Reputation: 115328
Good question.
There are several solution.
The first is the following. Run browser not directly but using script (shell for unix, bat file for windows) that will report you the process ID of the browser that it runs. Then use kill -9 PID
on linux and taskkill
on windows.
This solution will require you writing scripts for different platform (at list for 2).
But I have other suggestion. If the URL that you are opening in browser is yours (I mean you can add some javascript there) you can do the following. The URL that you are opening will create AJAX call to server. When you close your application you should say to server to send command to the browser to close it. At this moment javascript that is running into the browser will close its window. This is the most cross-platform solution.
BTW I think that the server that is used by mentioned AJAX component may be your own application. And the signal that you send to the AJAX component is just connection error. Really, if your application is the server and you are closing it, the AJAX call will fail. This 100% means that the browser should be closed too.
Upvotes: 0