13

Assuming I've got these two facts right :-

CreateProcess() starts a process and lets your program continue while it runs, but when your program finishes, the child process goes down with it. Furthermore, your program has to take note of when the child process exits so that it can properly release the process handle.

system() starts a process, waits for it to complete then continues with your program.

  • what I need to know is how to start a process and let it run independently of my program, and persist after my program exits. I don't need to capture its output or have any further control over it, I just want to let the user interact with it - like say I wanted to write an alternative to the Start Menu Run command.

So is it, please, actually possible to do that?

Luca Martini
  • 1,434
  • 1
  • 15
  • 35
user1285392
  • 139
  • 1
  • 3

2 Answers2

8

CreateProcess() does not wait for child process to finish by default, it returns immediately. Use WaitForSingleObject if you want to wait. No, the child process is not killed automatically when the parent exits, and the handle is anyway freed automatically by the operating system, so no need to do it yourself (if you use a modern version of windows).

Just like any OS resource (gdi objects, user objects, kernel objects), if you don't destroy/release/close the resource yourself then you will have resource leaks while your application runs. You should close both handles returned from CreateProcess soon after CreateProcess returns.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • Are you sure the child process is not killed automatically when parent exits? I've observed exactly that behavior, which led me to this question. – user4815162342 Dec 21 '16 at 20:06
  • 1
    I observe the same. Unless you specify DETACHED_PROCESS in the creation flags, the parent does actually take down the child. – Antonio Sanchez Apr 15 '17 at 20:41
5

You can specify "DETACHED_PROCESS" in CreationFlags Like the following code snippent:

if (CreateProcessW(NULL, (LPWSTR) L"File.exe ",
        0, 0, false,CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW | DETACHED_PROCESS , 0, 0,
        &siStartupInfo, &piProcessInfo) != false)
    {
        /* Watch the process. */
        dwExitCode = WaitForSingleObject(piProcessInfo.hProcess, (2 * 1000));
    }
    else
    {

        /* CreateProcess failed */
        iReturnVal = GetLastError();
    }

This will make yur processes independent. I hope this helps you.

Desphilboy
  • 962
  • 13
  • 13
  • 1
    It makes no sense to combine the Flags `CREATE_NO_WINDOW` with `DETACHED_PROCESS`. The `CREATE_NO_WINDOW` flag is ignored if the application is not a console application, or if it is used with either `CREATE_NEW_CONSOLE` or `DETACHED_PROCESS`. See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx – Jens A. Koch Feb 10 '17 at 14:52