Hi Daniweb,
My project was to create a basic shell. One of the features being if we enter a command and input a path to an executable, CreateProcess is invoked to start the process.

This works fine enough for console applications: the process starts, runs, and then terminates, upon which control is passed back to my shell.

However, there seems to be a gaping wide hole for WinAPI applications. The process starts sure enough, however if I press the X button to close the program, the window closes, however the parent process (my shell) is still in a suspended state. Further, if I open the task manager, I see that the process is actually running, and I have to close it from there.

Here is the code:

void runproc(string progpath){
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION  pi;
    char *szExe = new char[progpath.length()+1];
    strcpy(szExe, progpath.c_str());

    if(CreateProcess(0, szExe, 0, 0, FALSE, 0, 0, 0, &si, &pi))
    {
        cout<<"Running..."<<endl;
       // optionally wait for process to finish
       WaitForSingleObject(pi.hProcess, INFINITE);

       CloseHandle(pi.hProcess);
       CloseHandle(pi.hThread);

       cout<<"Success!"<<endl;
    }
    else{
        delete [] szExe;
        throw "Unable to execute file";
    }
}

So how do I ensure that the process is TERMINATED and then control returns to my shell?

Solved. The issue lay with the program I was testing it with continously. The code actually does wait till the process is terminated, and with my test subject, that never happened upon pressing the X button.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.