Is it possible to create a windows service to create and maintain another process? Like I'm writing a program, and say a virus killed the process, could I have my window service running and basically 'watching' it? I already have the code for a regular application that stays running and executes a program if it's not currently running, to keep it running.
I've never written a service before, but would it be that hard to just write this simple program, which basically runs a check to see if the process is running, if not, it executes it and sleeps for a few minutes?
Thanks.
Yes, it is possible. It is not uncommon to see third-party apps have watchdog services to keep them running in case of crashes. A service can enumerate running processes using EnumProcesses(), and if the desired executable is not running then start a new copy of it using CreateProcessAsUser().
If the service is the one starting the executable process in the first place, or can find it after an enumeration, one optimization would be to keep an open handle to the process (returned by CreateProcess...(), or use OpenProcess() on the process ID an enumeration returns), and then use a wait function, like WaitForSingleObject(), to detect when the process stops running. That way, you don't have to enumerate processes to find out if the intended process is still running or not.
Related
So, the profiler is written in c++ and is launched by the CLR automatically when the process to be profiled is launched. The process then launches another application (the main target of profiling). Profiler is launched for this process also. All this is taken care of, but the problem is:
Only one of these two profilers can communicate with the front end application via NamedPipe. I need both the profilers to write on the same pipe so that the front end application remains straight-forward and simple. Is this possible using some kind of semaphore to ensure that one of the processes write to the pipe at one time? I use the CreateFile() function to open the pipe in the profiler.
After starting a process with QProcess::startDetached, how can I stop it later?
Say the main program runs, then starts the detached process, which runs independently. The user closes the main program, then later opens it up again and wants to stop the process. How would I find the process and then stop it?
Is there a way I could prevent the application from the same process twice?
No, it will be decoupled from your application. You could get the the PID of it and then send a SIGSTOP on Linux, but this is platform specific and will not work without POSIX support, like with msvc. You would need to hand-craft your version therein.
Is there a way I could prevent the application from the same process twice?
Yes, by using lock file in the detached process. If that detached process happens to be written in at least partially Qt, you could use the QLockFile class.
If you happen to detach some platform specific process, then you have the same recurring issue again, for sure.
Here's the answer I figured out:
I first start the detached process that generates a unique id. That process write to a file whenever it runs (was a 1 minute timer). When it runs, it writes its id to a file. Then, if there happens to be another one that ran, if it sees a previous one ran, it just writes its id to the file and doesn't run, then, when the next one runs, it sees if its id is already in the file and if it is, it shuts itself off and clears the file, then the next run ends up running freely, being the only one running. This may end up skipping some time.
You can add a timestamp, too, as that might indicate it wasn't run recently and help with deciding whether or not to shut it down. The issue was if I just write the id to a file, when I turn the phone off, the file will say it's still running. The same applies to if it crashes.
On my system there is an application (App.exe) that runs, but sometimes it terminates (gracefully and expectantly). At the same time I have another application that, when App.exe is stopped, needs to perform certain tasks. So I need a way to monitor App.exe from my application.
Something like the following is what I am trying to accomplish
If (App.exe is running wait 360 seconds for it to terminate)
if (App.exe is not running anymore)
do the work I need to do when App.exe is NOT running
So, they KEY is:
how do I evaluate if App.exe is running
how do I wait 360 seconds for it to close (if it is still running)
Now this is not very difficult if my Application is the onw that started/spwaned App.exe (using CreateProcess and WaitForExit stuff), but in this case I am not the controlling agent ... so how do I monitor to see if App.exe is still running and consequently wait (for period of time X) for it to end before doing something specific?
Any hints, help, or recommendantions would be much appreciated.
Thanks,
You can use the ToolHelp APIs (CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS and Process32Next) to get the process id of any running app.exe processes. From that you can use OpenProcess to get a handle which you can then use wait on for termination.
How about a call to FindWindow to get the handle(or handles if the app can have multiple instances, or changes its title based on open documents), a call to GetWindowThreadProcessId and OpenProcess to convert it, then a call to WaitForSingleObject?
I believe you could use GetProcessesByName().
Is there some portable way to check the number of parallel instances of my app?
I have a c++ app (win32) where I need to know how often it was started. The problem is
that several user can start it parallel (terminal server), so i cannot search the "running process" list because I'm not able to access the the list of other users.
I tried it with Semaphore (boost & win32 CreateSemaphore)
It worked, but now I have the problem if the app crashes (Assertion or just kill the process) the counter is not changed. (rebooting helps)
Also manually removing/resetting the semaphore counter in my code is not possible because I don't know if somebody else is running my application.
Edited to add:
Suppose you have a license that lets you run 20 full-functionality copies of your program. Then you could have 20 mutexes, named MyProgMutex1 through MyProgMutex20. At startup, your program can loop through the mutexes. If it finds a spare mutex that it can take, it stops looping and enters full-functionality mode. If it loops through all the mutexes without being able to take any of them, then it enters reduced-functionality mode.
Original answer:
I assume you want to make sure that only one copy of your process runs at once. (Or, for Terminal Server, one copy of your process per login session).
Your named semaphore solution is close. The right way to do this is a named mutex. Use CreateMutex to make the mutex, then call WaitForSingleObject with a timeout of zero. If WaitForSingleObject returns WAIT_TIMEOUT, another copy of the process is running. If it returns WAIT_OBJECT_0 or WAIT_ABANDONED, then you are the only copy of the process. You need to keep the mutex handle open while your program runs - either call CloseHandle when your process is about to exit, or just deliberately leak the handle and rely on Window's built-in cleanup to release the handle for you when your process exits. Windows will automatically increment the mutex's counter when your process exits.
The only thing I can think of that mitigates the problem of crashed processes is a kind of “dead man’s switch”: each process needs to update its status in regular intervals. If a process fails to do this, it’s automatically discarded from the list of active processes.
This technique requires that one of the processes acts as a server which keeps tab of whether other processes have updated recently. If the server dies, then another process can take over. This, in turn, requires that each process tests whether there still is a server alive.
Alternatively, each process can be its own server and keep track locally. This may be easier to implement than server-switching.
You can broadcast message and other instances of your application should send some response. You count responses - you get number of instances.
Is it possible to have a program restart automatically if it crashes?
Something like:
An unhandled exception is thrown.
Release all resources allocated by process.
Start over and call main.
I would like this behavior for a server application I'm working on. If clients miss use the server it can get a std::bac_alloc exception, in which case I would like the server to simply restart instead of crashing and shutting down, thus avoiding manual startup.
I've done this before in Windows by running said program from another program via a win32 CreateProcess call. The other program then waits on the "monitored" process to exit, and calls its CreateProcess() again if it does. You wait for a process to exit by performing a WaitForSingleObject on the process' handle, which you get as one of the return values from your CreateProcess() call.
You will of course want to program in some way to make the monitoring process shut itself and its child process down.
Let Windows be your watchdog. You can call ChangeServiceConfig2 to set the failure actions for your service. (If your server isn't a service, then you're doing it wrong.) Specify SERVICE_CONFIG_FAILURE_ACTIONS for the dwInfoLevel parameter, and in the SERVICE_FAILURE_ACTIONS structure, set lpsaActions to an array of one or more SC_ACTION values. The type you want is SC_ACTION_RESTART.
I did something similar by implementing a watchdog. The watchdog ran as a service and would wait for a ping (called petting the dog) from the monitored process. If the monitored process died due to an exception, watchdog would cleanup and relaunch the application.
In case the application was not responding(no ping in a certain time) the watchdog would kill it and then restart it.
Here is a link to an implementation that you might want to use:
http://www.codeproject.com/KB/security/WatchDog.aspx
(PS: I implemented my own version but I cannot post it here. I found this from a quick google search and have no first hand experience with this particular implementation.)
If you just catch the exception, it should be possible to just restart your server by internal programming logic without completely restarting the whole program.
Like #T.E.D., we've done this in an application we built. Our application is a windows service, so the helper program stops the service (eventually kill it, if it hangs) and start the service again.