Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a process and make it 'independent'

Tags:

c++

winapi

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?

like image 862
user1285392 Avatar asked Mar 22 '12 08:03

user1285392


2 Answers

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.

like image 126
Desphilboy Avatar answered Oct 03 '22 18:10

Desphilboy


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.

like image 26
NullPoiиteя Avatar answered Oct 03 '22 17:10

NullPoiиteя