Majid D. L. Majid D. L. - 3 months ago 14
C++ Question

Starting Process and identify it later

Right now i'm programming a cron-like scheduler in c++. My program is able to start jobs at specific times and schedules them correctly.
What leave me troubles is check if a process still exists.

So i have a map JobMap; which is filled with process Handles as keys and Jobs as values.
How can i bring those two values in relation? I'm stuck at the point that whenever i try GetExitCodeProcess it never returns STILL_ACTIVE. Is it possible to set a unique token/key for a process so i can identify it and bring it in relation with a job?

Any idea would be a great help, thanks a lot!

void Cron::CheckRunningJobs()
{
DatNowObj Today;
DWORD exitCode = 0;

// now iterate through the executed jobs and check their state
for(MC_STL_PTR(MapPtr,JobMap)) //MapPtr is a pointer for my map
{
DatStrNowObj Today; //gives actual date
DWORD exitCode = 0;
PROT()<<"Job Handle:"<<MapPtr->first <<"Job in Map: "<<MapPtr->second.Job->getDescription()<<endl;

// store the exit code for later use
MapPtr->second.exitCode = GetExitCodeProcess(MapPtr->first, &exitCode);
if(GetExitCodeProcess(MapPtr->first, &exitCode) == STILL_ACTIVE)
{
PROT()<<"PROCESS STILL ACTIVE"<<endl;
}
else if(GetExitCodeProcess(MapPtr->first, &exitCode) == ERROR_INVALID_FUNCTION)
{
CloseHandle(MapPtr->first);
continue;
}
else if(MapPtr->second.execTime)
{

}
else if(GetExitCodeProcess(MapPtr->first, &exitCode) == 0)
{
CloseHandle(MapPtr->first);

JobMap.erase(MapPtr);

PROT()<<"Job in Map after Erase: "<<MapPtr->second.Job->getDescription() << "and Map size: " << JobMap.size()<<endl;
continue;
}
else
{
PROT()<<"Error:"<<GetLastError()<<endl;
continue;
}

}
}

Answer

Please read the documentation that user6545984 linked. You seem to be getting very mixed up here.

GetExitCodeProcess() returns a BOOL indicating whether the function succeeded, not the process. You're trying to compare against that BOOL using constants as if it's an exitCode. But they're incompatible types. Even if they weren't, I have no idea why you would keep calling the function over and over again!

To get the exit code, you need to pass in an LPDWORD pointer to receive it. Call the function once, get the two outputs into the right variables - one return value, one output argument - and respond to those appropriately.

So, you need to change at least this

MapPtr->second.exitCode = GetExitCodeProcess(MapPtr->first, &exitCode);

to something like

BOOL result = GetExitCodeProcess(MapPtr->first, &MapPtr->second.exitCode);

or wherever else you want to store said code - then update all your comparisons to match, and also add comparisons to result if you need to.

Comments