windows C program perform action on shutdown - c

I am making a program that sends "heartbeats" for a server to keep track of nodes. They are packets with the following payloads:
'start' when it starts up
'running' every 5 seconds
'stopping' at shutdown
The first two are easy. The thread/loop can set the message on first and subsequent runs. How do I make the loop "catch" a shutdown so that it can send a last packet?
I use the minGW compiler for C in WinXP platform.
Edit: I added the relevant details I missed (thanks walkingTarget and Ferruccio)
It is an in-progress app that contains messy stuff in implementation :-)
It uses libCURL, the HTTP client library to send the packets
It is a console app, which I (much later) intend as a service
It needs to save a file and send a packet at shutdown
It needs to capture a system shutdown

In your WindowProc() you can check for the message WM_QueryEndSession, which Windows sends to all open processes before shutting down. For more info on that message see the following link, but i understand that it is as trivial as checking for a WM_SIZE:
http://msdn.microsoft.com/en-us/library/aa376890%28VS.85%29.aspx

Related

UEFI networking edk2 simple example

I am looking for the simplest/easiest way to implement some sort of networking communication using edk2 in a UEFI application. I do not care what type of protocol is being used, but it shall not be UDP.
I have read similar questions, tried a bit on my own but failed, and my problems are;
-A good test environment(Using a VM currently, running UEFI 2.5, not sure if sufficient/is a good way)
-What protocols/solutions are good?
What I need to accomplish is;
uefi application loads, sends a packet containing "Hello" to Server(IP can be known, no need to resolve IP from url)
Server sends "Hello" to the Client, and the UEFI application will print the reply. It is very simple, but this has been overwhelming and the information out there is limited from what I have seen.
All help/insight/information is appriciated.
There is a complete HTTP sample program in the UEFI specification (Chapter 29.6.2.1).
There is also a complete UDP sample on stackoverflow, if you want to use TCP you just need to connect to the server before sending data. The method and field names are nearly the same in the TCP and UDP protocols.
All higher level network protocols work in the same way.
Create a child instance, search for the ServiceBinding protocol and call CreateChild
Get the protocol from the child instances handle
Configure the child instance (XYZ->Configure(...))
TCP only: Create a Connect Token
TCP only: Call XYZ->Connect(...) and wait till it completes
Create a Transmit/Request Token
Call XYZ->Transmit(...)/XYZ->Request(...) and wait till it completes
Create a Receive/Response Token
Call XYZ->Receive(...)/XYZ->Response(...) and wait till it completes
Go back to 6 or 8 if you need to transmit/receive more data
TCP only: Create a Close token
TCP only: Call XYZ->Close(...) and wait till it completes
Destroy the child instance (ServiceBinding->DestroyChild(...))
You may call XYZ->Poll(...) while you are waiting for the network operations to complete.

I don't know how to get orders from the terminal in a multithread situation

I am working on an UDP Socket project. I use 2 threads in my client program. The first thread registers and maintain connexion with the server. The second thread needs to answer some orders from the terminal, for example sending the configuration of the client to the server.
I would need to be able to type onto the terminal when the program is running to inform the second thread of what it needs to do but I don't know how to implement it in my code, and I don't even know what to look for on google.
I haven't tried anything since I have absolutely no idea how to do this
I would like to be able to type "sendconf" for example in the terminal while the program is running and have the second thread answering to that. I know how to send the configuration of the client to the server, I just don't know how to inform the thread it needs to do this.
Message queues?
Add a "message" (the command) to a queue that the second thread polls, it then processes the message and sends a reply to another queue which is polled by the first thread.
If you want to be synchronous instead, the second thread can instead set data directly in the message structure for the reply, and then set a flag that it's finished. The first thread keeps waiting on the flag and then gives the result to the user.

Tibco RV C client stops receiving messages

I've got a C client listening to Tibco RV (using 8.4.0). The source pumps out messages on PREFIX1.* and PREFIX2.* pretty frequently (can be several times per second).
I have six threads, each listening to a particular SUFFIX, eg PREFIX1.SUFFIX_A and PREFIX2.SUFFIX_A. So each thread has a listener and its own queue for these two messages. I've got a queue size limit of 1000, dropping the oldest 200 if we hit that (but never have more than about 40 in the queue at busy times).
After running fine for many hours, each day the program suddenly stops receiving data. The source continues to publish but I no longer dispatch events from any queue. I don't understand what can have caused this (aside from deleting the listeners).
What might have caused the listening to stop? Or alternatively, given the system is high frequency how can this be investigated? Can I tell whether a listener is still active via the C interface? I couldn't see anything in the API for that.
Thanks for any help,
-Dave
It looks like the problem was that the machine had only a partial install of RV. In particular, there was no rv daemon in the package that we had for that machine. I'm actually a bit confused how we managed to get network data at all after re-reading the docs but it seems that without a daemon we can achieve networking until a minor network problem, then nothing; with the daemon we recover from network errors.
So the fix for this case was simply to install the full package and ensure the daemon runs constantly. Now the problem appears to have disappeared.

How to find where a process is stuck using DDD

I have a TCP Svr process written in C and running on CentOS 5.5. It acts as a TCP Server for external clients and also does some IPC communication with other processes in the system using Unix Domain Sockets it has establised. It's not a multi threaded process. It does one task at a time. There's an epoll_wait() I use to listen for requests on either the TCP socket or any of the IPC sockets it has established with internal processes. When the epoll_wait() function breaks,I process the request for whoever it is and then go back into epoll_wait()
I have a TCP Client that connects to this Process from outside (not IPC). It connects sucessfully, sends a request msg, gets a response back. I've put this in an infinite loop
just to test out its robustness etc.
After a while, the TCP Server stops responding to requests coming from TCP Client. The TCP client connects successfully, sends a request message, but it doesnt get any response msg back from the TCP server.
So I reckon the TCP server is stuck somewhere else, trying to do something and has not returned to the epoll_wait() to process
other requests coming in. I've tried to figure it out using logs, but thats not helping me understand where exactly the process is stuck.
So I wanted to use any debugger that can give me some information (function name would be great), as to what the process is doing. Putting breakpoints, is overwhelming cause the TCP Server process has tons of files and functions....
I'm trying to use DDD on CentOS 5.5, to figureout whats going on. I attach to the process successfully. Then I click on "Step" or "Stepi" or "Next" button....
but nothing happens....
btw when I use Eclipse for debugging, and attach to this process (or any process), I always get "__kernel_vsyscall()"....Does this mean, the program breaks by default at
whatever its doing? If thats the case, how do I come out of the __kernel_vsyscall() call, to continue within my program? If I press f8, it comes out, but then I dont know where it was, since I loose the stack trace....Like I said earlier. Since I cant figure where it was, I dont know where to put breakpoint....
In summary, I want to figureout where my process is stuck or what its doing and try to debug from that point on....
How do I go about this?
Thanks
Amit
1) Attaching to a C process can often cause problems in itself, is there any way for you to start the process in the debugger?
2) Using the step functions of DDD need to be done after you've set a breakpoint and the program is stopped on a command. From reading your question, I'm not sure you've done that. You may not want to set many breakpoints, but is setting one or two in critical sections of code possible?
In summary, What I wanted to accomplish was to be able to find where my program is stuck, when it hangs. I figured it out - It was so simple. Create a configuration in Eclipse ...."Debug Configurations->C/C++ attach to application"...
Let the process run normally from shell (preferably with a terminal attached). When it hangs, open eclipse, click on the debug icon and run the configured process. It'll ask you to attach to a process. Look for your process name and attach to it.
Now, just look at the entire stack trace....you'll see some of your own function calls mixed with kernel function calls. That tells you where the program is stuck.

Cleanest way to stop a process on Win32?

While implementing an applicative server and its client-side libraries in C++, I am having trouble finding a clean and reliable way to stop client processes on server shutdown on Windows.
Assuming the server and its clients run under the same user, the requirements are:
the solution should work in the following cases:
clients may each feature either a console or a gui.
user may be unprivileged.
clients may be or become unresponsive (infinite loop, deadlock).
clients may or may not be children of the server (direct or indirect).
unless prevented by a client-side defect, clients shall be allowed the opportunity to exit cleanly (free their ressources, sync some data to disk...) and some reasonable time to do so.
all client return codes shall be made available (if possible) to the server during the shutdown procedure.
server shall wait until all clients are gone.
As of this edit, the majority of the answers below advocate the use of a shared memory (or another IPC mechanism) between the server and its clients to convey shutdown orders and client status. These solutions would work, but require that clients successfully initialize the library.
What I did not say, is that the server is also used to start the clients and in some cases other programs/scripts which don't use the client library at all. A solution that did not rely on a graceful communication between server and clients would be nicer (if possible).
Some time ago, I stumbled upon a C snippet (in the MSDN I believe) that did the following:
start a thread via CreateRemoteThread in the process to shutdown.
had that thread directly call ExitProcess.
Unfortunately now that I'm looking for it, I'm unable to find it and the search results seem to imply that this trick does not work anymore on Vista. Any expert input on this ?
If you use thread, a simple solution is to use a named system event, the thread sleeps on the event waiting for it to be signaled, the control application can signal the event when it wants the client applications to quit.
For the UI application it (the thread) can post a message to the main window, WM_ CLOSE or QUIT I forget which, in the console application it can issue a CTRL-C or if the main console code loops it can check some exit condition set by the thread.
Either way rather than finding the client applications an telling them to quit, use the OS to signal they should quit. The sleeping thread will use virtually no CPU footprint provided it uses WaitForSingleObject to sleep on.
You want some sort of IPC between clients and servers. If all clients were children, I think pipes would have been easiest; since they're not, I guess a server-operated shared-memory segment can be used to register clients, issue the shutdown command, and collect return codes posted there by clients successfully shutting down.
In this shared-memory area, clients put their process IDs, so that the server can forcefully kill any unresponsive clients (modulo server privileges), using TerminateProcess().
If you are willing to go the IPC route, make the normal communication between client and server bi-directional to let the server ask the clients to shut down. Or, failing that, have the clients poll. Or as the last resort, the clients should be instructed to exit when the make a request to server. You can let the library user register an exit callback, but the best way I know of is to simply call "exit" in the client library when the client is told to shut down. If the client gets stuck in shutdown code, the server needs to be able to work around it by ignoring that client's data structures and connection.
Use PostMessage or a named event.
Re: PostMessage -- applications other than GUIs, as well as threads other than the GUI thread, can have message loops and it's very useful for stuff like this. (In fact COM uses message loops under the hood.) I've done it before with ATL but am a little rusty with that.
If you want to be robust to malicious attacks from "bad" processes, include a private key shared by client/server as one of the parameters in the message.
The named event approach is probably simpler; use CreateEvent with a name that is a secret shared by the client/server, and have the appropriate app check the status of the event (e.g. WaitForSingleObject with a timeout of 0) within its main loop to determine whether to shut down.
That's a very general question, and there are some inconsistencies.
While it is a not 100% rule, most console applications run to completion, whereas GUI applications run until the user terminates them (And services run until stopped via the SCM). Hence, it's easier to request a GUI to close. You send them the equivalent of Alt-F4. But for a console program, you have to send them the equivalent of Ctrl-C and hope they handle it. In both cases, you simply wait. If the process sticks around, you then shoot it down (TerminateProcess) and pray that the damage is limited. But your HDD can fill up with temporary files.
GUI application in general do not have exit codes - where would they go? And a console process that is forcefully terminated by definition does not exit, so it has no exit code. So, in a server shutdown scenario, don't expect exit codes.
If you've got a debugger attached, you generally can't shutdown the process from another application. That would make it impossible for debuggers to debug exit code!

Resources