Stop Java process on application exit - c#

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).

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,
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.)
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.
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.

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.

Related

How to terminate another application using c++/c#/vc++ gracefully?

I have an application running an infinite loop and performing some important functions in that loop. I need to provide the user with another application which would terminate the application with infinite loop. The problem is what if the user terminates the application when it is inside loop performing some operation. It would lead to inconsistent state. I tried kill() and TerminateProcess but they didn't help. Is there any way I could signal the application with infinite loop that complete your iteration and exit? I am open to solutions in c#,cpp and vc++.
EDIT:
The source code for looping program is accessible.
While there are many variations on Interprocess Communication, for this purpose a simple event will suffice.
In the process you need to control:
hEvent = CreateEvent() (with a name, make it sufficiently unique)
Periodically check it with WaitForSingleObject(hEvent, ZERO_TIMEOUT)
From the process to do the controlling:
hEvent = OpenEvent() passing the same name
SetEvent(hEvent) will cause the return value from WaitForSingleObject in the other process to change.
A slightly nicer way might be to start a background thread in the main application which creates a window and a taskbar icon with an Exit option on its menu. Then you only need to share an event between threads, not between processes, which removes the requirement for a unique name.
an application running an infinite loop and performing some important functions
As long as it does "important functions", the program in question has a way to obtain new input data from somewhere (e.g., from a file or from a network socket). Therefore, you can add a special token into input data with a meaning "end of operation". Upon receiving such token, the program will know that it is time to shut itself down. One of the simplest tokens of such nature are end-of-file for regular files or remote side socket closure.
The method I just described is simple and is what may be called "in-band control channel". That is, you use a single channel to both feed data to process and commands to control (even if there is just one command, "stop").
An alternative to that would be "out of band control channel", that is, a second channel to pass commands between applications.
The problem is what if the user terminates the application when it is inside loop performing some operation. It would lead to inconsistent state.
Your attempts to use kill is one possibility to use facilities known as inter-process signals. To use it properly, the receiving program must register a signal handler routine to initiate a shutdown on its own. The sender should use a matching signal number. Using kill (SIGKILL in POSIX) is not the best choice because it has a special behavior and cannot be assigned with a custom signal handler. In POSIX, it is better to use SIGUSR1 or one of many other signals. I do not remember native Windows equivalents for that.
There is a multitude of mechanisms to organize an inter-processor communication between processes in a conventional operating system, see Wikipedia to a full list for everything from a shared file to named pipes and network sockets. Choose one that suites your needs best. You only need to pass a single bit of data, so basically the one that is the easiest to program is the best.

Possible to run a function before "rudely" interrupting a program? [duplicate]

We have a .NET console app that has many foreground threads.
If we kill the process using Task Manager or issuing killjob, kill from the command line in windows, is there a way by which we can gracefully shut down the application (adding manged code within the .net console app), something like having a function being called say TodoBeforeShutdown() that disposes objects, closes any open connections, etc.
P.S. - I read the other threads and they all suggested different ways to kill the process, rather than my specific question, what is the best way we can handle a terminate process, within the .NET managed code.
Thanks in advance.
Unfortunately, there is no event raised that you can handle whenever a process is killed.You can think of killing a process like cutting off the power to the computer—no matter what code you have designed to run on system shutdown, if the computer doesn't shut down gracefully or properly, that code is not going to run.
When you kill a process using Task Manager, it calls the Win32 TerminateProcess function, which unconditionally forces the process (including all of its owned threads) to exit. The execution of all threads/processes is halted, and all pending I/O requests are canceled. Your program is effectively dead. The TerminateProcess function does not invoke the shutdown sequence provided by the CLR, so your managed app would not even have any idea that is was being shut down.
You suggest that you're concerned about disposing objects whenever your application's process is terminated, but there are a couple of things worth pointing out here:
Always strive to minimize the amount of damage that could be done. Dispose of your objects as early as possible, whenever you are finished with them. Don't wait until later. At any given time, when your program's process is terminated, you should only be keeping the bare minimum number of objects around, which will leave fewer possibilities for leaks.
The operating system will generally clean up and free most of these resources (i.e., handles, etc.) upon termination.
Finally, it should go without saying that process termination in this way is truly an exceptional condition—even if some resources leak, that's to be expected. You're not supposed to shut an app down this way any more than you're supposed to kill necessary Windows system processes (even though you can when running as an Administrator).
If this is your regular plan to shut down your console application, you need to find another plan.
In short: You can't!Killing a process is exactly the opposite of a gracefull exit.If you are running Foreground Threads, sending a wm_exit won't shut down your app. Since you have a console app, you could simply redirect the console input to send an "exit" to your process.Further I think you could change the app to service (instead of a console application), this would offer you exactly what you are looking for -> interface for gracefull exit based on windows build-in tools/commands.

Process continues running after main thread has terminated?

I'll start by saying I do not have a lot of experience in troubleshooting multi-threading problems. So a lot of what I've read about debugging race conditions, dead locks, live locks, etc. are strictly theoretical to me.
I have this .NET application that is making use of a dynamically loaded native win32 dll. If the dll is never loaded the application terminates without a problem. However, if the dll is loaded then when the user exits the application the UI disappears but the process never terminates.
I've turned on native code debugging in the project settings so I can see all the threads that are running. When the user closes the application window the main thread appears to terminate. I know this because if I perform a Break All in the Threads windows in Visual Studio the main thread is re-categorized as a worker thread and there is no call stack available for it. There are 20 other threads still active, all with call stacks. I've looked through the call stacks for all of these threads and nothing sticks out at me (there's no mention of the dll in any of the call stacks).
What steps can I take to narrow down the cause of this problem? Are there any additional tools I should be using to help pin point the problem?
This means that some of your Foreground Threads are still alive. Unlike Background Threads, Foreground Threads keeps the process alive.
You should either use Background Threads or Stop your Foregrounds Threads to be able to exit the process gracefully.
Windows application will automatically exit when all of its thread(s) are stopped.
As you said
If the dll is never loaded the application terminates without a
problem
I'm assuming all the running threads are unmanaged threads(not created by clr). There is no concept of background threads in native code. All threads must be terminated to terminate the process.
You must find a way to signal all threads to exit in that library. See if you have any api exposed for that.
If you don't find anything, you've got a "Sledge Hammer" approach. i.e Terminate the process with Environment.Exit which works almost always. Be sure you use this approach as a last resort as this can corrupt the process state.

Stop application from exiting

I'm working on a Windows application (not WinForms, not Console, not WinService), is just a project with an entry class.
What is the best way, in .NET, to stop an application from exiting the Main method?
I know I can achieve this in console with Console.Read() or I can use EvenWaitHandle.WaitOne() and never call Set().
Is there a better way of doing this?
Thanks for the help in advance.
UPDATE:
This is an overview of the application.
I need to start independent processes (some exe) on demand, containing wcf service. WCF service should listen idefinetly and that is why I need this functionality. The most similar approach I can find is IIS (many w3wp processes running at the same time).
w3svc.exe (IIS windows service) starts many instances of w3wp.exe depending on the number of configured app pools and the requests, it receives.
In my application I want to keep up the processes representing w3wp.exe in the IIS infrastructure, not w3svc. What is the kind of message loop that would keep alive w3wp in .NET?
You can do that in sooo many ways. I personally like this one, as it is very readable and self explanatory:
Process.GetCurrentProcess().WaitForExit();
IIS is a windows service which is why it runs like this. You might look at other options like a single service where you can invoke it via an api and tell it to start another thread or listener. Starting new instances of applications isn't the best option. Typically windows applications have a messagepump, which is a while loop I think...which would prevent it from exiting.
However, you can also follow the example here, which I believe does not close the formless window:
Run Formless Notification User Control?
while(true)
{
// to make it less CPU intensive
Thread.Sleep(1000);
}
Of course, any solution you can think of will not prevent the forceful termination of application by killing its process.
In your update you say that the program is starting several other programs using Process. (It happens to be 'yourself' but that doesn't matter.)
If the program has already done that it doesn't sound like it has any more to do. That process ending won't kill all of the processes it spawned.
You can use the process.WaitForExit() to wait for the processes that you spawn to all exit, rather than just spinning doing nothing, if for some reason you really need to keep the process alive. If there is something that it actually needs to do after spawning the other processes then you'd need to tell us what that is, because if there is something you should be waiting on an event of some sort, which is something you haven't brought up.
Edit: you claim that all the process is doing is "listening". Define that task. If you have a blocking GetNextRequest method then you simply have: while(true){GetNextRequest();}. If it's non blocking, then use use a BlockingCollection<MyRequests> in which the receive method/event hanlder adds a new item to the collection and the main thread had a while loop just like I mentioned before reading from the blocking collection. The point is that you shouldn't ever just sit there and do nothing; you process is doing something, so do that in a while(!done) or while(true) loop. If the method isn't blocking, it's a reasonably well defined problem to solve; just wrap it in a blocking method call.
System.Threading.Thread.Sleep(millisenconds);

How to detect when main thread terminates?

What I need to know:
I would like to detect when a the main thread (process?) terminates so that I can ensure certain actions are performed before it is terminated.
What I have found myself:
I found the events AppDomain.DomainUnload and AppDomain.ProcessExit. AppDomain.DomainUnload seems to work with non-applications like MbUnit. AppDomain.ProcessExit seems to work with applications but there is a 3 second time limit which I really don't like. Is there more ways to detect when an AppDomain / process terminates?
Background:
I am looking for such an event to ensure my log is persistet to file when the application terminates. The actual logging runs on another thread using a producer-consumer pattern where it is very likely that log entries might queue up in memory and I need to ensure this queue is saved to file when the application terminates.
Is there anything else I should be aware of?
Update:
Changed the above to reflect what I have found out myself. I am not happy with the 3 second time limit during ProcessExit. The MSDN documentation does say though that it can be extended:
The total execution time of all
ProcessExit event handlers is limited,
just as the total execution time of
all finalizers is limited at process
shutdown. The default is three
seconds, which can be overridden by an
unmanaged host.
Does anyone know how to override the default?
More ideas are also highly appreciated!
Follow up:
I have posted a follow up question to this.
You should have an entry point for your application. Normally you can do there some logging when all tasks are terminated:
static void Main()
{
try
{
Application.Run( .... );
}
finally
{
// logging ...
}
}
What exactly do you want to find out?
When the process terminates? (Just because the AppDomain is unloaded doesn't necessarily mean that the entire process is terminating)
When the main thread terminates (If there are other non-background threads, the main thread can terminate without the process terminating (or AppDomain unloading)
So they're not quite the same thing.
Anyway, it is generally dangerous to have log messages buffered in memory at all. What happens if someone turns off the power? Or if I terminate your process through Task Manager? All your log messages are gone. So often, you'll want unbuffered writes in your log, to get messages pushed to disk immediately.
Anyway, another (more robust) approach might be to run the logger itself in a non-background thread. That way, even if the rest of the application terminates, the logger won't, so the process is kept alive. Then you just have to set some flag when the rest of the app terminates, to let the logger know that it too should close once it has written out all pending log messages.
It still won't save you from the case where the system loses power or someone forcibly termianates the process on the OS-level, but it will handle all cases where the application closes normally, and gives you unlimited time to perform clean-up actions (since the process isn't actually terminating yet, it's still got one live thread)
ie. guaranteed to be called and have unlimited time to finish?
Unfortunately, NO option is going to have unlimited time, and be guaranteed. There is no way to enforce this, as many things can happen. Somebody tripping over the power cord or a forced termination of your program will prevent any option from giving you adequate time to handle things.
In general, putting your logic at the end of the Main routine is probably the most reasonable option, since that gives you complete freedom in handling your termination events. You have no time constraints there, and can have the processing take as much time as needed.
There are no guarantees that this will run, though, since a forceful termination of your program may bypass this entirely.
Based on the documentation, it looks like the default application domain (the one your Main method is probably running in) will not receive the DomainUnload event.
I don't know a built-in event that would do what you expect.
You could define your own custom event, have interested parties register with it, and fire off the event just before you return from Main().
I don't know how old this thread is, but I've had a similar problem whcih was a little tough for me to solve.
I had a WinForms application that was not firing any of the above forementioned events when a user logged out. Wraaping the Application.Run() in a try finally didn't work either.
Now to get around this you would have to using PInvoke into Win32 API's to achieve this. Well you did prior to .NET 2.0 anyways. Luckly MS introduced a new class called SystemEvents. With this class you can catch a SessionEnd event. This event allows you to cleanup when the OS want to terminate your app. There is no .NET time limit o this event it appears, although the OS will eventually kill your app if you take too long. This is a little more than 3 seconds, although 3 seconds should be plenty of time to cleanup.
Secondly my other problem was I wanted my worker thread to terminate the main thread once it was finished its work. With an Application.Run() this was hard to achieve. What I ended up doing was calling Application.Run() with a shared Application context. The thread is then able to call ApplicationContext.ThreadExit() to force the Application.Run to return. This seems to work quite nicely.
Hope this helps someone.
Regards
NozFX

Categories

Resources