AnArrayOfFunctions
AnArrayOfFunctions

Reputation: 3764

How to quit a running batch?

Consider the following program:

main(){system("start /b batch.bat");}

I want to terminate the batch and any processes spawned by it sometime later in my program - any ideas?

Upvotes: 0

Views: 95

Answers (1)

RbMm
RbMm

Reputation: 33794

I want to terminate the batch and any processes spawned by it sometime

for this exist Job Objects :

A job object allows groups of processes to be managed as a unit.

To terminate all processes currently associated with a job object, use the TerminateJobObject function.

if (HANDLE hJob = CreateJobObjectW(0, 0))
{
    WCHAR ApplicationName[MAX_PATH];
    if (GetEnvironmentVariableW(L"ComSpec", ApplicationName, RTL_NUMBER_OF(ApplicationName)))
    {
        PROCESS_INFORMATION pi;
        STARTUPINFOW si = { sizeof(si) };
        if (CreateProcessW(ApplicationName, L"cmd /c <some path>/batch.bat", 
                0, 0, 0, CREATE_SUSPENDED, 0, 0, &si, &pi))
        {
            if (AssignProcessToJobObject(hJob, pi.hProcess))
            {
                ResumeThread(pi.hThread);
            }
            else
            {
                TerminateProcess(pi.hProcess, 0);
            }
            CloseHandle(pi.hThread);
            CloseHandle(pi.hProcess);
        }
    }

    // .. wait for something ...
    TerminateJobObject(hJob, 0);
    CloseHandle(hJob);
}

however new proceeses can be launched say via remote com calls (StartService for example) - formally from another process. this of course will be not in job and not terminated

Upvotes: 1

Related Questions