Cmd.exe: how to start a background process, run some things, stop background process

background-processbatchcommand-line-interface

I want to run a batch script that:

  • starts a background process (a Selenium RC server, if that matters);
  • waits until the background process starts to listening some port (or wait a fixed amount of time);
  • run some instructions;
  • stops the background process.

I wrote this:

start java -jar "path\selenium-server.jar" 
ping -n 5 127.0.0.1 >NUL
"path\Gallio.Echo.exe" "path\MyAssembly.dll"
REM now, how do I stop the background process?

Best Answer

You say "DOS", but I'd imagine you're meaning the Windows CMD shell. (MS-DOS isn't a multitasking operating system, after all.)

Okay, okay-- Here's a hack that I just worked up. I feel kinda dirty even suggesting this.

SET TASK=%RANDOM%-SELENIUM-SERVER-%RANDOM%
start "%TASK%" java -jar "path\selenium-server.jar"
ping -n 5 127.0.0.1 >NUL"
path\Gallio.Echo.exe" "path\MyAssembly.dll"
taskkill /FI "WINDOWTITLE eq %TASK%"

Assuming that the "java" command doesn't much with the window title, that "START" command will set the window title to "random number"-SELENIUM-SERVER-"random number", and then the TASKKILL will kill any windows with that title.

Eww... that makes me feel dirty.

If the "java" does mess with the window title, you could also do:

SET TASK=%RANDOM%-SELENIUM-SERVER-%RANDOM%
start "%TASK%" cmd /k start java -jar "path\selenium-server.jar"
ping -n 5 127.0.0.1 >NUL"
path\Gallio.Echo.exe" "path\MyAssembly.dll"
taskkill /T /FI "WINDOWTITLE eq %TASK%"

That really makes me feel dirty. That creates a CMD window with the random title that, in turn, starts the "java" in a separate window. The "/T" on TASKKILL will kill any child processes of the "FOO" window-- namely the "java" window.

I feel sick. >smile<