3

In my java project I need to run VLC Media Player (for steaming) and on request I want to stop streaming. In Linux, I have created following bash script, which runs the VLC process with some arguments and then outputs it's ID to standart output:

cvlc $@ &
echo $!

Then I have following java code which runs the script and reads it's ID from stdin:

Process proc = Runtime.getRuntime().exec("/path/to/script");
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
if(line!=null) {
    lastPID = new Integer(line);
    System.out.println("Last vlc PID=" + lastPID);
}

When I want to stop streaming, I will kill process with corresponding ID:

Runtime.getRuntime().exec("kill " + lastPID);

Is there any way to write equivalent script in Windows 7 (cmd.exe or Windows PowerShell)? Alternatively, is there a way to write pure (platform independent) java code which runs process, then gets it's ID and stops it?

wallyk
  • 56,922
  • 16
  • 83
  • 148
Blasterex
  • 31
  • 2

2 Answers2

1

There is the way. But why don't you try to terminate the process using pure java API? User process.destroy(). It is exactly like kill PID.

To get process ID you can use WMI. Check out the following resource: http://blogs.technet.com/b/heyscriptingguy/archive/2006/06/01/how-can-i-find-the-process-id-associated-with-a-batch-file.aspx

You can run your process with some kind of identifier passed as additional parameter and then perform WMI select from Win32_Process where ... and put the criteria into the where clause. But again, you actually do not need this.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Use this method: How to get the PID of running application in Windows?

Then call this using the PID:

Runtime.getRuntime().exec("taskkill /F /PID " + PID_To_Be_Killed);
Community
  • 1
  • 1
user1449265
  • 357
  • 1
  • 2
  • 11