How to limit process memory

On Linux you can always do something like

	ulimit -v 1024

This command limits the amount of available virtual memory for processes which will run by current user.

On Windows 2000+ the only way to place constraint on the memory for a process is to use jobs. Among other useful features jobs allow to apply some restrictions to a group of processes. So if one needs to limit available virtual memory for a process he must create a job, initialize the job with some values and assign the target process to that job object.

Here is the sample code required to restrict memory usage:

	JOBOBJECT_EXTENDED_LIMIT_INFORMATION Limits;
	HANDLE hJob;
	Limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
	Limits.ProcessMemoryLimit = 1024 * 1024 * 1; // 1 MB
	hJob = CreateJobObject(NULL, NULL);
	assert(SetInformationJobObject(hJob,
		JobObjectExtendedLimitInformation,
		&Limits,
		sizeof(Limits)));
	assert(AssignProcessToJobObject(hJob,  GetCurrentProcess()));

Note that setting size of the Working Set would not help in limiting the available virtual memory. Working Set is the amount of memory which is available at any given time in RAM for the process. The bigger size of a working set the more pages are placed in RAM instead of being swapped.

If a process has large working set the system needs more available RAM memory to give control to this process. With large working set process will wait longer to get CPU time.
If a process has small working set it will take some additional time to retrieve newly required pages from swapping space.

Leave a Reply