user1586792
user1586792

Reputation: 23

Stop Java process on application exit

I am currently trying to write a windows form application (in C#) that can start and stop multiple Java processes (with parameters to run a specific jar file).

I have no problem starting each process; however I need to find a way to make the application close all of them when it exits, regardless of which way (being an unknown amount of java processes), that I run in an individual worker thread each to avoid tying up the main thread while the application is running (and catching the processes outputs).

I had a look at this one: Close another process when application is closing

but it does not seem to work for my purpose (it doesn't close the processes).

Upvotes: 1

Views: 2371

Answers (2)

vladr
vladr

Reputation: 66681

it does not seem to work for my purpose.. (it doesn't close the processes).

But what does it do? Does it close the Java window(s) at least? Do your Java applications even have windows?

In general,

  1. If possible (i.e. if you build the Java application yourself) you should set up a mechanism between your C# and Java application(s) to gracefully signal the Java application(s) to shut down (socket, etc.)
  2. Failing that, you may still be able to gracefully shut down your Java application(s), if they are graphical, by sending WM_CLOSE. This is what the Process.CloseMainWindow/Process.Close approach that you tried (and failed) does. If your Java applications are console applications, you can try closing its/their standard input and/or simulating ^C instead.
  3. Finally, when all else fails, use Process.Kill to terminate your Java child process(es) -- ungracefully. You may want your controlling process to first try 1. or 2. above, wait until either all child processes have exited or until a short period of time (e.g. 3s) has elapsed, and only then proceed with Process.Kill on whatever processes have not exited already.

Upvotes: 1

Ravindra Bagale
Ravindra Bagale

Reputation: 17655

procrss.kill The Kill method is an excellent way to cause a Process to meet a violent and swift end. The Kill method can throw some exceptions. But it often does not and usually will accomplish your desired objective—which is somewhere between cold-blooded murder and a swift and painless execution.

Upvotes: 0

Related Questions