I'm looking to build a task monitor/manager using the Win32 API. It will be started (preferably as a windows service) with a command line argument specifying how many instances of a new process it should start.
task_man.exe 40
Will start 40 instances of the process
task.exe
Now, whenever a task.exe exits (correctly or not), I will have to start a new one to replace it.
My rough idea is this:
Start the tasks from task_man, get their PIDs, and then have a loop that checks whether the PIDs are all active processes. For every invalid PID, start a new process and replace the old PID with the new one.
Is there a better design I can use, or a better workflow? Is there a standard method for doing this? I don't want to reinvent the wheel... Also, which APIs should I look into?
I'm also looking for a design that is easy to change afterwards - i.e. if I run
task_man.exe 30
afterwards, a new task_man shouldn't start running, but rather it should change the number of 开发者_Python百科tasks in the previous instance. (I know it will start running, what I'm saying it should modify the original and then exit)
I'm not looking for code (as in I'm not looking for the full implementation, not that I mind looking over samples), rather what APIs I can use, or suggestions on the overall design I came up with.
The easiest way to tell if a process has exited is to wait on its handle. You can do that in a few ways:
- Build an array of all the process handles, and use WaitForMultipleObjects (bWaitAll being FALSE) to wait on all of them. Then, when your code continues, you'll have to figure out which process ended, create a new one, update the array and wait again.
- Run 40 threads, each creating one process and infinitely waiting on its one handle (using WaitForSingleObject). Then, when that task ends, that thread will be responsible to create a new one and wait on it.
- If you don't want to create 40 threads, just have one that will wait for short periods of times over each of the process handles (using WFSO), and check the return value. Your program will response slower this way, but it would be easier to recognize the process that has ended, and you won't be creating many threads.
If you want to replace pooling with wait operations, you can use WaitForSignalObject/WaitForMultipleObjects for created processes. Process handle becomes signaled when the process exits. Unlike pooling, wait operations don't consume CPU. Waiting thread is inactive unless one of objects is signaled.
精彩评论