Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know child process status and resource usage on windows?

I want to write a program, which will launch a child process. The child process may be windows mode or console mode program.

I want to monitor the child process status and resource usage. e.g. I want to know the child process is still running or terminated. If it terminated, I want to know the reason (is terminated normally or because of crash?).

And during the child process running and/or it terminated, I want to know its resource usage, especially CPU time (user time, system) and memory usage (virtual size and/or rss). It is OK if the numbers are not very accurate.

In Unix terminology, I want to fork, exec, waitpid and getrusage . And fork+setrusage+exec can limit child's resource usage. But I don't know how to do these on the Windows platform.

Please point me the Windows API name. I could study the rest myself.

Prefer not using library other than the Windows API. Prefer it is not parent working as debugger and attaching to child process. Just not prefer, but still acceptable.

like image 819
kcwu Avatar asked Feb 28 '23 18:02

kcwu


1 Answers

When you call CreateProcess, it returns a handle to the process.

WaitForSingleObject on a process handle will block until the process has exited or time-out has expired. A timeout of zero will return immediately and indicate if the process is still running.

BOOL IsProcessRunning(HANDLE process)
{
    return WaitForSingleObject(process, 0) != WAIT_OBJECT_0;
}

void WaitForProcessToExit(HANDLE process)
{
    WaitForSingleObject(process, INFINITE);
}

To get the exit code of a running process, you can use GetExitCodeProcess. You'll need to interpret what the error code means, however. 0xC0000005 is typical for an access violation, but not all crashes result in this error code.

For resource usage, you can call GetProcessTimes to get total CPU time, GetGuiResources to get GDI handle info, GetProcessMemoryInfo to get memory stats, and GetProcessIoCounters to get IO info.

like image 58
Michael Avatar answered Apr 08 '23 18:04

Michael