Hi @Kenster ,
Thank you for the detailed write-up and for separating the three association paths. I went through the Win32 documentation for the limit, association, enumeration and termination APIs involved. Below is what the documentation confirms, what it leaves open, and a cleanup design that doesn't depend on the open part.
In short:
- No, the documented Win32 contract doesn't give that guarantee, for any of the three paths. The zero limit is documented as a check on each association attempt. No page defines how an attempt that is already in progress is ordered against
SetInformationJobObject.JobObjectBasicProcessIdListis a point-in-time list, so a PID list read after the limit is confirmed isn't guaranteed to include a process from such an attempt. - There is no documented barrier for in-flight associations, but you can complete the cleanup without one.
TerminateJobObjectand the job'sActiveProcessescounter both work at job level, and the counter goes up when an association is attempted. Repeat the termination until the counter reads 0, and put a gate around your own launch code. That removes the dependency on the PID snapshot (point 4).
1. What the documentation confirms, and what it leaves open
Confirmed:
- JOBOBJECT_BASIC_LIMIT_INFORMATION: "If you try to associate a process with a job, and this causes the active process count to exceed this limit, the process is terminated and the association fails." The Remarks add that the system "increments the active process count when you attempt to associate a process with a job". For a process rejected by the limit, the count goes down only when the process "terminates and all handles to the process are closed".
- AssignProcessToJobObject fails, and terminates the process, when the active process limit would be exceeded. It also fails "If the job or any of its parent jobs in the job chain is terminating when AssignProcessToJob is called".
- TerminateJobObject "Terminates all processes currently associated with the job", including all of its child jobs, "as if TerminateProcess were called for each process". TerminateProcess is asynchronous.
-
ActiveProcessesin JOBOBJECT_BASIC_ACCOUNTING_INFORMATION is "The total number of processes currently associated with the job". Per Nested Jobs, a job's accounting includes the processes in its child jobs, and each child job contains a subset of its parent's processes. - During process creation, a child "is associated with every job in the job chain of its parent process", and breakaway stops at the first job that doesn't permit it (Nested Jobs). So if your job doesn't allow breakaway, children that processes in your job tree create with
CreateProcessstay associated with your job.
Not documented:
- How an association that is already in progress, on any of the three paths, is ordered against a concurrent
SetInformationJobObjectcall. - Whether
JobObjectBasicProcessIdListreflects an association that completes during or right after the query. JOBOBJECT_BASIC_PROCESS_ID_LIST only describes the identifiers "returned by this call". - Whether your job's zero limit is checked for an association that targets one of its child jobs. The nesting documentation doesn't address the active process limit.
- Any API that seals a job or waits for in-flight associations.
2. The three paths
-
PROC_THREAD_ATTRIBUTE_JOB_LIST: UpdateProcThreadAttribute documents it as "a list of job handles to be assigned to the child process, in the order specified". The assignment happens insideCreateProcessW. How it is ordered against a concurrent limit change isn't described. - Implicit inheritance:
- This is the default for children created with
CreateProcessby a process in the job (Job Objects). - It also applies to
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, where the child inherits the job of the specified parent. So a process outside your job can create a child inside it if it hasPROCESS_CREATE_PROCESSaccess to a member. - Processes started through WMI's
Win32_Process.Createare not associated with the job at all, so no job-level cleanup covers them.
- This is the default for children created with
-
AssignProcessToJobObject: the limit rule and the "is terminating" rule above describe the outcome of a call. They don't say how a call is ordered against a concurrentSetInformationJobObject.
For all three paths, the documented rule says what happens to an attempt made under the zero limit. It doesn't say when an attempt that was already running gets checked.
3. Windows 10 and Windows Server 2016 onward
None of these pages has a version note that adds this guarantee, so I'd treat it as unspecified on your whole baseline. What you see on build 26200 for new attempts matches the documented rule; only the in-flight ordering is open.
Two version notes matter for your baseline:
- Nested jobs exist from Windows 8 and Windows Server 2012, so child jobs are possible on every version you support.
-
PROC_THREAD_ATTRIBUTE_JOB_LISTis available from Windows 10 and Windows Server 2016.
All APIs in the sketch below are available on that whole baseline.
4. Documented mechanisms, and a cleanup that doesn't rely on the PID snapshot
What the documentation offers:
- Barrier: nothing you can trigger on demand.
- JOBOBJECT_END_OF_JOB_TIME_INFORMATION describes a state where "No additional processes can be assigned to the job". It only applies after the end-of-job time limit fires, and that limit depends on user-mode time, which the system checks periodically.
-
AssignProcessToJobObjectalso fails while the job "is terminating". The docs don't say how long that state lasts, and they don't apply it to the other two paths.
- Whole-job termination:
TerminateJobObject, andJOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSEwhen the last job handle is closed. Neither depends on a PID list; both act on the processes associated with the job at the time they run. - Whole-job completion: the
ActiveProcessescounter. Completion-port messages such asJOB_OBJECT_MSG_ACTIVE_PROCESS_ZEROwork as a wake-up, but their delivery is not guaranteed, so re-read the counter after each one.
Your sequence already has the right pieces. The main change is to decide completion at job level rather than from the PID list. The steps below add a gate before your step 1 and replace steps 3 and 4:
- a) Stop your own launches. Run every
CreateProcessW+JOB_LISTcall, and every create-suspended +AssignProcessToJobObjectsequence, under a shared SRW lock. Cleanup sets a closing flag, then takes the lock exclusively. When that returns, none of your own association calls is still running. - b) Apply the zero limit with a query-modify-set of
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, the pattern recommended in the SetInformationJobObject remarks. Flags such asKILL_ON_JOB_CLOSEstay as they are, and the breakaway flags are cleared. - c) Drain at job level: call
TerminateJobObjectand re-readActiveProcessesuntil it reads 0. - d) Close the job handle last. With
KILL_ON_JOB_CLOSE, closing the last handle terminates all associated processes. This also covers the case where your cleanup process exits unexpectedly while holding that handle.
#include <windows.h>
#include <atomic>
// Sketch only: error handling trimmed.
// hJob needs JOB_OBJECT_QUERY, JOB_OBJECT_SET_ATTRIBUTES and JOB_OBJECT_TERMINATE.
static SRWLOCK g_launchGate = SRWLOCK_INIT;
static std::atomic<bool> g_closing{ false };
// a) Every association your own code makes goes through this gate.
// Keep the create and the assign inside the same launch() call.
template <class Launch>
bool LaunchThroughGate(Launch&& launch)
{
AcquireSRWLockShared(&g_launchGate);
const bool ok = !g_closing.load() && launch();
ReleaseSRWLockShared(&g_launchGate);
return ok;
}
// c) Job-level drain: no PID snapshot involved.
static bool DrainJob(HANDLE hJob, UINT exitCode, ULONGLONG timeoutMs)
{
const ULONGLONG deadline = GetTickCount64() + timeoutMs;
for (;;)
{
TerminateJobObject(hJob, exitCode); // repeated on every pass on purpose
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION acct = {};
if (!QueryInformationJobObject(hJob, JobObjectBasicAccountingInformation,
&acct, sizeof(acct), nullptr))
return false;
if (acct.ActiveProcesses == 0)
return true;
if (GetTickCount64() >= deadline)
return false; // log acct and the PID list here
Sleep(10); // termination is asynchronous
}
}
bool CleanupJob(HANDLE hJob, UINT exitCode, ULONGLONG timeoutMs)
{
// a) Stop your own launches and wait for any that are still running.
g_closing.store(true);
AcquireSRWLockExclusive(&g_launchGate);
ReleaseSRWLockExclusive(&g_launchGate); // later launches see g_closing and return false
// b) Zero limit via query-modify-set, keeping the other flags.
JOBOBJECT_EXTENDED_LIMIT_INFORMATION lim = {};
bool ok = QueryInformationJobObject(hJob, JobObjectExtendedLimitInformation,
&lim, sizeof(lim), nullptr) != FALSE;
if (ok)
{
lim.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
lim.BasicLimitInformation.LimitFlags &= ~(JOB_OBJECT_LIMIT_BREAKAWAY_OK |
JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK);
lim.BasicLimitInformation.ActiveProcessLimit = 0;
ok = SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
&lim, sizeof(lim)) != FALSE;
}
// c) Drain at job level.
if (ok)
ok = DrainJob(hJob, exitCode, timeoutMs);
return ok; // d) close hJob after this
}
Why this covers in-flight associations: the drain ends only when ActiveProcesses reads 0 after the zero limit is in effect. Per the counter rules above, an association is counted from the moment it is attempted until the process has exited. Two cases follow:
- An in-flight association that was counted before the limit took effect keeps the count above 0 until a later
TerminateJobObjectpass has terminated its process. - An association attempted after the limit took effect is rejected by it.
This is my reading of the documented counter rules, not an explicit ordering statement. Unlike the PID snapshot, though, it doesn't depend on seeing each process.
Things to keep in mind:
- A process rejected by the limit stays counted until all handles to it are closed. If the drain times out, look for such a handle. One example is the
hProcessyour launcher still holds after a failedAssignProcessToJobObject. - The gate only covers your own code. Don't give other processes a job handle with
JOB_OBJECT_ASSIGN_PROCESSaccess: keep the job unnamed and its handle non-inheritable. If you create child jobs, set the zero limit on them too. - If you keep the PID list for logging, check any handle you open with IsProcessInJob, because a PID can belong to a different process by the time you open it.
5. Confirmation from Windows engineering
On the documentation side, I can confirm it. None of the pages above states this guarantee for any of the three paths, and none documents a barrier for in-flight associations. Under the published contract, this ordering is therefore unspecified on Windows 10, Windows Server 2016 and later. A statement about the implementation itself has to come from Windows engineering.
If you need that, for example for a design or security review, I recommend opening a case through Windows Developer Support, under Technical support for app platforms. They can advise whether the question can be routed to Windows engineering. Please note that this is a paid support option. You can also use the feedback option on those reference pages to ask for the in-flight behavior to be documented.
I hope this helps with your cleanup design. If you find this answer helpful, I'd appreciate it if you could follow this guide so others with the same question can benefit from it as well.