Limiting user processor time and peek virtual memory with Job Objects

790 views Asked by At

I'm writing an application runner on Windows which can limit processor user time and virtual memory for the application it will run. Idea is to have following:

runner.exe mem_limit_in_MB time_limit_in_sec command.exe command_arguments ...

My investigation lead me to Windows Job Objects API and since I'm trying to do all that from C#, I found JobObjectWrapper to help me.

The main part of the code if following:

using (JobObject jo = new JobObject())
{
    // Time
    jo.Limits.PerProcessUserTimeLimit = TimeSpan.FromMilliseconds(limitTime);
    jo.Events.OnEndOfProcessTime += new jobEventHandler<EndOfProcessTimeEventArgs>(Events_OnEndOfProcessTime);

    // Memory
    jo.Limits.ProcessMemoryLimit = new IntPtr(limitMemory);
    jo.Events.OnProcessMemoryLimit += new jobEventHandler<ProcessMemoryLimitEventArgs>(Events_OnProcessMemoryLimit);

    // Process
    ProcessStartInfo psi = new ProcessStartInfo(command, arguments);
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;

    jo.Limits.IsChildProcessBreakAway = false;
    Process p = jo.CreateProcessSecured(psi);

    p.WaitForExit();
}

Now, the problem is that it seams that Events_OnEndOfProcessTime is not called timely. If I set 0.5 sec limit for an app that takes several minutes, depending on the run application is once terminated after 0.5 sec and sometimes after 4 sec. Why is this happening? I cannot find any reference if Job Objects are checking limits periodically or in real-time.

My question is two-fold: - Does anyone know about already developed code that does what I need? - Does anyone know if Job Objects are executed periodically or in real time?

Thanks in advance...

1

There are 1 answers

1
Arno On BEST ANSWER

PerProcessUserTimeLimit specifies the amount of user-mode time is granted to the process.

"The system periodically checks to determine whether each process associated with the job has accumulated more user-mode time than the set limit. If it has, the process is terminated." (MSDN)

Consequently it depends on your application, particulary on how effient it is burning user-mode time. Ending a process with PerProcessUserTimeLimit = 0.5 after 0.5 sec. means that it has used ~100% cpu (user-mode) during that time.

... if Job Objects are executed periodically or in real time? Periodically, as stated above.