When does a Windows thread need a message loop and why? - windows

When do I need a message loop in a Windows application?
For example, for a Windows service do I need a message loop for every thread that I created or just for the main service process?
while(true)
{
GetMessage(&messageHandle, 0, 0, 0);
DispatchMessage(&messageHandle);
}

Every native Windows programs contains at least one message loop (often called a "message pump") like the one you give an example of.
This is to enable the handling of Windows events initiated by the program itself, other applications or the operating system.
Example of Windows events can be for timers, socket communication, GUI actions, clipboard, etc.
Many APIs and frameworks implement a message loop for you. This will depend on what you are using in your particular case.
(Check the answers in this Stack Overflow question for more information on message loops/message pump.)
Now to the gist of your question: many or most programs will work fine with one message-loop. The cases where you would want more than one is typically if processing a Windows event can take a long time (i.e. it locks the current thread) and there are requirements that require you too keep processing new window events. I can think of two concrete examples:
One is in a GUI application where you're showing a modal dialog (which usually freezes the main message pump and spins up a new one for the dialog)
A service of some kind where processing of I/O events can take a long time because of external dependencies and timeliness of processing of new I/O events is critical
In (1) this is very often a consequence of the GUI framework you are using and not something you have to do explicitly. In (2) a better way of handling it would be to asynchronously "do the work" of each event rather than blocking the message pump.
In conclusion: it depends. :-) In most cases you shouldn't need to use more than one message loop, but if you have to, do it!

Apps:
Essentially, when the thread is going to create and manage windows. This includes 'hidden' windows that support COM STA and the like.
No windows, no windows messages, no message loop required.
Services:
Service manager needs to handle the service messages, and so requires a service message loop for Start/Stop/whatever.
For other threads started in a service, no message loop is required.

Related

Detect UI operation which will "hang" the application if running in service mode

Fellow experts!
I have faced the following dilemma: some of our tools (executables) are started as scheduled tasks, some are started as services and others as usual desktop apps with interactive Windows user. We are using the code sharing strategy for source management (this is not debatable for this question).
So the solution I want to find is the following:
Detect UI operation at run-time which leads to hanging service/background task (such as say call to Application.ShowException, ShowMessage, MessageDialog, TForm.Show etc.). And when such an action detected I want to raise the exception instead. Then the operation will fail, we will have stack trace etc. but the process will not hang up! The most problematic hang up is when some event processing is done in transaction and then in some of the code used to process event suddenly (because of error in code, design, whatever) there is UI code executed then the process hangs and the DB parts can be locked!
What I think I need to do is: Use DDetours library to intercept WinAPI calls to a certain routines and raise exception instead (so that the process does not hang, but just fail in some method). Also I know that the creation of forms and windows does not hang the app, but only the tries to show them to the user.
Is there some known method of handling this problem? Or maybe there is some list of WinAPI routine set which hangs in service mode?
Thank you in advance.

Is it possible to track a PostMessage between processes?

We have a system where there are typically two processes running on the same system. One process handles the GUI and the other runs like a service (although for historical reasons, it's not a service, just an exe with no visible window).
The two processes undertake IPC mainly via registered messages asynchronously - i.e. we use RegisterWindowMessage() in both processes to define a large'ish set of messages that effectively form the API to the server process.
I have written a "hands-free" monitoring application that uses SetWindowsHookEx() to monitor and display the message queues of both processes and provide some level of decoding of the way the API is being utilised and how notifications are being propagated to the GUI process (each individual window can subscribe to notifications from the server directly).
So, there are a large number of messages in both directions so I have filtering and summary counts etc. so I can focus on particular activity. All this can be done without affecting the live code, which is good.
This all works well, but it now would be very useful to be able to "tag" a message originating in the GUI so I can trace the same message when it's processed by the server. This would be enormously useful for debugging and diagnosing system issues, but I can't find a clean way (actually I can't find any way!) of doing this without adding such support to our registered message API, which would be a lot of work and involves more risk than I'm comfortable with at the moment. It gets further complicated by the fact that the server pre-processes some messages and then does a PostMessage() back to itself to perform the action, so the originating message can get "lost".
Has anyone here tackled this type of problem? If so, can you give me some pointers? If not, then are there any documented or undocumented ways of adding a small block of data to a Windows message and retrieving it later? I've looked at SetMessageExtraInfo() but that seems to be per-queue rather than per-message.
FindWindow or FindWindowEx will give you the details of the GUI Window. Compare the details with message intercepted

What Windows IPC method is better for short commands?

I need one way IPC method for 2 Windows applications (both on the same machine).
Which one is better in case that my applications are CLI based + windows service.
P.S. I've implemented message queue in destination process (CLI application) in separate thread. And posting my message from source process (GUI application) via PostThreadMessage.
So. When both applications were run from the same user - everything is OK. When I'm running my destination application via Task Scheduler under Local Service user I'm getting 1444 error code (Wrong Thread ID).
Any ideas?
P.P.S. From MSDN
This thread must have the SE_TCB_NAME privilege to post a message to a thread that belongs to a process with the same locally unique identifier (LUID) but is in a different desktop. Otherwise, the function fails and returns ERROR_INVALID_THREAD_ID.
This thread must either belong to the same desktop as the calling thread or to a process with the same LUID. Otherwise, the function fails and returns ERROR_INVALID_THREAD_ID.
So. I should determine how to setup SE_TCB_NAME to my thread from my source process.
WM_COPYDATA message or custom message code (if you don't plan to transfer text or binary data) would work. WM_COPYDATA message lets you transfer binary data and Windows does copying across process boundaries itself.
In GUI -> CLI application you would need to create an invisible window in CLI process to receive messages (if you want messages to be SENT and not POSTed from the GUI application). If you just POST messages from GUI to CLI, then PostThreadMessage() function would be enough and there's no need for a window.
In CLI -> GUI direction there are no complexities at all as the window is already (usually) present in GUI application.
There is also nice solution - Message Queue from boost library.

How can I programmatically detect that a mac app has "beachballed"?

I would like to create an application that will monitor apps running on my machine, and respond to situations where an application has beachballed. Is it possible (using any of the various OSX programming tools -- I'll teach myself Objective-C for this) to detect whether this has happened? If so, can someone give me a short code sample that does so?
I'm afraid I don't the actual classes or functions involved, but I can give you an outline of the process.
First, understand that every Application (perhaps every Window) has an event queue backing it. Each is serviced by a thread that just pops an event* off the queue, does some processing, and then returns to waiting for the next event. A "beachball" comes up (when forced by the system) when the event queue isn't getting serviced quickly enough. A "frozen" event queue implies that an application locked up when responding to some event in the past.
Now - outside of debugging contexts - you shouldn't be able to reach into another application and fiddle with a thread's event queue to see if its getting serviced. But what you could do instead is periodically post an event that would illicit a response, and if ever that response doesn't come you know the application is "locked up".
This constitutes polling, so be wary of the performance implications.
*Events are things like key down, key up, mouse moved, repaint, and so on.
Besides the WindowServer itself, the other system components that I know of that can detect unresponsiveness are the force quit dialog, spindump (which collects sampling profiles of applications while they are unresponsive), and Activity Monitor (presumably via its pmTool privileged subprocess). Perhaps running strings on pmTool might provide hints about what system calls to use?
Note that none of these evidently does its job by polling, because no application is ever detected as unresponsive until it fails to respond to an event — if an application hangs/does a lot of computation without checking its event queue, but it receives no events during that time, then it is not reported as unresponsive.

What Windows API to look into for building a scheduling application?

Why not use the Windows scheduler?
I have several applications that have to run at certain times according to business rules not the typical every weekday at 1pm.
I also need a way for the applications to provide feedback of their progress so that I can have rules that notify me when the applications are running slow or aren't even running anymore.
What Windows API should I be looking into? (like, a time version of the FileWatcher apis)
What's the best way to have the application notify the scheduler of its progress (files, sockets, windows messages, ???)?
For Vista/Win2k8, there's the nice Task Scheduler 2.0 API: http://msdn.microsoft.com/en-us/library/aa384138(VS.85).aspx. Previous version have the Task Scheduler 1.0 API, but I've never used it.
AppControls has a CronJob component that you can use to create scheduled events. This saves your program from having to wake up every minute and check the schedule itself. Instead, just schedule the job and indicate a callback method.
I have used this component for scheduling jobs myself and have been very happy with the way that it works.
I think what you really want is a common framework for your applications that report to something (you or the system messages or tracing or perfmon, event log, whatever) and also to receive via some inter process protocol a way to receive messages and respond.
based on the reporting you can change the scheduling or make changes, etc.
So, there is some monitor app, and then each of your other apps does common reporting.
events I can think of:
- started
- stopped
- error
- normal log messages
- and of course specific things your apps do.
I think there are probably existing classes/framework that do this - you'll have to check around.
If it were me, I would make a service that could talk to all the other apps and perhaps was even an http server. It would be able to route messages to particular apps and start stop those processes and query them.
There are lots of ways to do what you want though. those were just off the top of my head.
Alternatively you might just be able to get these to be services and they handle messages sent to them. Their normal processing does nothing until they are "woken up" with some task command.
You have more questions in one. Normally you should split them. But let's overlook this and try to answer.
To schedule certain events (including running an application): Use TJvScheduledEvents from JVCL. IMHO JVCL is the best Delphi open source library around with extensive number of components, developers & support. TJvScheduledEvents is quite neat, uses threads for event scheduling and also you have in JVCL a detailed editor for your events (it needs a small hack to use it though).
To provide 'feedback' from your applications to a (remote) central point: A very very very good solution (if your requirements permit) is to log the progress of your applications in a table (let's call it LOG) on a Firebird server. In LOG you can have the following fields: COMPUTER, USERNAME, APPNAME, MSG, LOGDATE (etc. etc.). In the After Insert trigger of the LOG table you can fire an event (let's call it NEW_LOG). In your console app you can register the interest for this event and so, your application will be automatically updated with everything which happens in any of your applications, so you can do log analysis, graphs etc. Of course you can do it with IB, but IB costs.
...going on Windows API route you need headers (which probably aren't translated), you'll encounter our dearest Pointers/PChars etc. etc. Of course, building from scratch everything isn't worthwhile but when this is already done in a Delphi way, why don't use it?
Use service with a timer that is fired regulary (for example each minute). It reads the schedule and looks if some are due before the next iteration. If so, you can execute them.
You can add an interface that shows all running apps. For the feedback and query that using a desktop application.

Resources