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.
Related
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.
I'm trying to build this server that receives connections on a socket, authenticates the user and then "sends" the socket to the class of the user that matches it(with the info given in the authentication), to be added to a thread pool (of the multiple devices of that client) to be processed (exchanging information, updating things elsewhere, etc..).
I chose to do it this way because I don't want to be sending requests to the server 24/7, just keep a lightweight thread open for each device, communicating with it in real time.
Now, all I've seen so far that might do something like this is Socket.DuplicateAndClose, but that works for processes, not threads.
So is anyone aware of any way to do this, or should I take a different approach?
Thank you.
EDIT:
It seemed that there was some confusion, what I meant was, move it to another Socket inside another class, then the threads open on that class will process it. If I accept the connection to authenticate it, that socket then is having that connection, beforehand I couldn't have known to accept it with the specific socket in the specific class because I didn't know where it came from, and now, I have a thread I can't do anything with because I can't tell that class to use this thread, because if I do and use it in a thread of that class, the next socket I use to accept the connection will be the one that's occupied by that same class. I could use a huge array to store accepted sockets and tell classes that that socket number was theirs, but that would not only be limited but a bunch of loose sockets as well, which would work but would be neither optimized or organized.
There is no restriction on which threads access a given socket.
Any thread can perform operations on any socket (providing the thread's process has an open handle to that thread).
Performing multiple IO operations of the same type (eg. two reads) concurrently on one socket is likely to lead to confusion – you cannot control which will get the next data, and it could then complete second. But any form of explicit or implicit concurrence control can be used to avoid that.
(The same applies to other kernel objects like files, named pipes, shared memory sections, semaphores, …. The only thing that is restricted is only the thread holding a mutex or critical section can release it.)
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.
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);
I was writing up a long, detailed question, but just scrapped it in favor of a simpler question that I didn't find an answer to here.
Brief app description:
I have a WPF app that spawns several threads, and each thread executes its own WF. What are some of the best ways to handle errors in the threads and WF that will allow user interaction from the GUI side? I definitely plan to handle any low level exceptions in the thread, because I don't want the thread to exit.
Summary of questions:
How have you implemented communication between WF and the thread that starts it? There is WorkflowTerminated, but I don't want the workflow to exit -- I need to fix the problem and let it continue. I assume the only option is using a FaultHandler, but was wondering if there's another way to do it without using an activity block. I am hoping there's a framework out there that I just haven't found yet.
The error from WF needs to get caught by the thread, which then needs to display the error in the GUI. The user will then make a logical choice for recovery, which should then be sent back to the thread, and then to WF. Again, is there something existing out there that I should take a look at?
Even buzzwords / keywords that accomplish what I am describing would be really helpful, and I can do the legwork on researching each of them. However, any additional insight is always welcome. :)
What's worked for me in multi-threaded WPF apps is to have the errant thread invoke a callback method that passes the exception and other info back to the UI thread. Callbacks can have return values, so if your thread can block while waiting for the user to respond, then that can work for you. Remember that the callback will run on the thread that calls it, so any UI updates have to be done via the control's dispatcher. You will have to decide whether all of the threads use the same callback and what kind of synchronization you'll need if there's a chance that multiple threads can throw exceptions simultaneously.
Here's how I ended up solving this problem. But first a little background info:
User clicks a button in the GUI that causes the candy packager to start running. This is done via a command binding in the ViewModel, which then calls a low-level function in the Model. The function in the model launches a thread and executes a state machine.
At some point, the machine will fail. When it does, I compile information about the error and possible (known) recovery methods. I put this into an object and then pass it to the GUI via a callback interface. In the meantime, the worker thread is stuck waiting for an Event to get set.
Eventually, the candy worker will notice the error and will click a button telling the system what to do. This results in two things: 1) it flags one of the recovery methods as the preferred one, and 2) sets the event. Now the worker thread continues on, checks for the preferred error recovery method and transitions into the respective state in the state machine.
This works very well (so far). The part I know is totally lame is the manner in which it checks for the preferred error recovery method. I am essentially setting a string variable, and then comparing this string to a list of known strings. Ultra lame, but I'm not sure of a better way to do this, other than using an enum. Does anyone have recommendations for me?