<p>In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this. </p>

<p>I want the child processes to be automatically closed <strong>if my main processes crashes</strong> or is closed.</p>

<p>Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.</p>

<p>How do I do this?</p>

[{'answer_id': 53212, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': -1, 'selected': False, 'text': "<p>You'd probably have to keep a list of the processes you start, and kill them off one by one when you exit your program.  I'm not sure of the specifics of doing this in C++ but it shouldn't be hard.  The difficult part would probably be ensuring that child processes are shutdown in the case of an application crash.  .Net has the ability to add a function that get's called when an unhandled exception occurs. I'm not sure if C++ offers the same capabilities.</p>\n"}, {'answer_id': 53214, 'author': 'jm.', 'author_id': 814, 'author_profile': 'https://Stackoverflow.com/users/814', 'pm_score': 7, 'selected': True, 'text': '<p>The Windows API supports objects called "Job Objects". The following code will create a "job" that is configured to shut down all processes when the main application ends (when its handles are cleaned up). This code should only be run once.:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL\nif( ghJob == NULL)\n{\n    ::MessageBox( 0, "Could not create job object", "TEST", MB_OK);\n}\nelse\n{\n    JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };\n\n    // Configure all child processes associated with the job to terminate when the\n    jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n    if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &amp;jeli, sizeof(jeli)))\n    {\n        ::MessageBox( 0, "Could not SetInformationJobObject", "TEST", MB_OK);\n    }\n}\n</code></pre>\n\n<p>Then when each child process is created, execute the following code to launch each child each process and add it to the job object:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>STARTUPINFO info={sizeof(info)};\nPROCESS_INFORMATION processInfo;\n\n// Launch child process - example is notepad.exe\nif (::CreateProcess( NULL, "notepad.exe", NULL, NULL, TRUE, 0, NULL, NULL, &amp;info, &amp;processInfo))\n{\n    ::MessageBox( 0, "CreateProcess succeeded.", "TEST", MB_OK);\n    if(ghJob)\n    {\n        if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))\n        {\n            ::MessageBox( 0, "Could not AssignProcessToObject", "TEST", MB_OK);\n        }\n    }\n\n    // Can we free handles now? Not sure about this.\n    //CloseHandle(processInfo.hProcess); \n    CloseHandle(processInfo.hThread);\n}\n</code></pre>\n\n<p>VISTA NOTE: See <a href="http://social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/71c9599e-a3d5-4b79-bfc1-1800565c5b8a" rel="noreferrer">AssignProcessToJobObject always return "access denied" on Vista</a> if you encounter access-denied issues with AssignProcessToObject() on vista.</p>\n'}, {'answer_id': 53216, 'author': 'Pedro', 'author_id': 5488, 'author_profile': 'https://Stackoverflow.com/users/5488', 'pm_score': 1, 'selected': False, 'text': "<p>You can keep a separate watchdog process running. Its only task is watching the current process space to spot situations like you describe. It could even re-launch the original application after a crash or provide different options to the user, collect debug information, etc. Just try to keep it simple enough so that you don't need a second watchdog to watch the first one.</p>\n"}, {'answer_id': 53218, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 3, 'selected': False, 'text': '<p>One somewhat hackish solution would be for the parent process to attach to each child as a debugger (use <a href="http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx" rel="noreferrer">DebugActiveProcess</a>).  When a debugger terminates all its debuggee processes are terminated as well.</p>\n\n<p>A better solution (assuming you wrote the child processes as well) would be to have the child processes monitor the parent and exit if it goes away.</p>\n'}, {'answer_id': 53227, 'author': 'Adam Pierce', 'author_id': 5324, 'author_profile': 'https://Stackoverflow.com/users/5324', 'pm_score': -1, 'selected': False, 'text': '<p>You could encapsulate each process in a C++ object and keep a list of them in global scope. The destructors can shut down each process. That will work fine if the program exits normally but it it crashes, all bets are off.</p>\n\n<p>Here is a rough example:</p>\n\n<pre><code>class myprocess\n{\npublic:\n    myprocess(HANDLE hProcess)\n        : _hProcess(hProcess)\n    { }\n\n    ~myprocess()\n    {\n        TerminateProcess(_hProcess, 0);\n    }\n\nprivate:\n    HANDLE _hProcess;\n};\n\nstd::list&lt;myprocess&gt; allprocesses;\n</code></pre>\n\n<p>Then whenever you launch one, call allprocessess.push_back(hProcess);</p>\n'}, {'answer_id': 53518, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 2, 'selected': False, 'text': '<p>Windows Job Objects sounds like a good place to start.  The name of the Job Object would have to be well-known, or passed to the children (or inherit the handle).  The children would need to be notice when the parent dies, either through a failed IPC "heartbeat" or just WFMO/WFSO on the parent\'s process handle.  At that point any child process could TermianteJobObject to bring down the whole group.</p>\n'}, {'answer_id': 69243480, 'author': 'Kohill Yang', 'author_id': 14881537, 'author_profile': 'https://Stackoverflow.com/users/14881537', 'pm_score': 0, 'selected': False, 'text': '<p>You can assign a job to the parent process before creating processes:</p>\n<pre class="lang-cpp prettyprint-override"><code>static HANDLE hjob_kill_on_job_close=INVALID_HANDLE_VALUE;\nvoid init(){\n    hjob_kill_on_job_close = CreateJobObject(NULL, NULL);\n    if (hjob_kill_on_job_close){\n        JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobli = { 0 };\n        jobli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n        SetInformationJobObject(hjob_kill_on_job_close,\n            JobObjectExtendedLimitInformation,\n            &amp;jobli, sizeof(jobli));\n        AssignProcessToJobObject(hjob_kill_on_job_close, GetCurrentProcess());\n    }\n}\nvoid deinit(){\n    if (hjob_kill_on_job_close) {\n        CloseHandle(hjob_kill_on_job_close);\n    }\n}\n</code></pre>\n<p><code>JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE</code> causes all processes associated with the job to terminate when the last handle to the job is closed. By default, all child processes will be assigned to the job automatically, unless you passed <code>CREATE_BREAKAWAY_FROM_JOB</code> when calling <code>CreateProcess</code>. See <a href="https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags</a> for more information about <code>CREATE_BREAKAWAY_FROM_JOB</code>.</p>\n<p>You can use process explorer from Sysinternals to make sure all processes are assigned to the job. Just like this:\n<a href="https://i.stack.imgur.com/DLERd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DLERd.png" alt="enter image description here" /></a></p>\n'}]
['https://Stackoverflow.com/questions/53208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/814/']