abdo.eng 2006210
abdo.eng 2006210

Reputation: 543

CreateProcess() launching child applications

I want to launching a sub application from the main application using CreateProcess function with the following steps:

  1. launched a sub .exe program from the main without window for the sub program
  2. wait for rand Sleep
  3. then terminate the sub application first then the main.

In the following my example code for the above but the sub program running with window(in this case NotePad) and i can't terminate the sub program.

#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <strsafe.h>
#include <direct.h>
#include <string.h>

int main(int argc, char* argv[])
{   

HWND                hWnd;
STARTUPINFO         sInfo;
PROCESS_INFORMATION pInfo;

ZeroMemory(&sInfo, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
ZeroMemory(&pInfo, sizeof(pInfo));

if (CreateProcess("C:\\WINDOWS\\System32\\notepad.exe", NULL, NULL, NULL, false, CREATE_NO_WINDOW, NULL, NULL, &sInfo, &pInfo))
{
    printf("Sleeping 100ms...\n");
    Sleep(100);

    DWORD dwExitCode;
    GetExitCodeProcess(pInfo.hProcess, &dwExitCode);

    CloseHandle(pInfo.hThread);
    CloseHandle(pInfo.hProcess);

    }

system("pause");

return 0;

 }

Upvotes: 2

Views: 9303

Answers (1)

Qaz
Qaz

Reputation: 61910

The reason the notepad window shows is because it's not a console application. MSDN says this about CREATE_NO_WINDOW:

The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.

Instead, use the STARTUPINFO you pass in:

sInfo.dwFlags = STARTF_USESHOWWINDOW;
sInfo.wShowWindow = SW_HIDE;

I believe that will affect the last argument to WinMain in Notepad's main function, but I'm not sure.

As for why notepad doesn't close, GetExitCodeProcess doesn't actually end the process, it just retrieves the state. You can use TerminateProcess instead:

TerminateProcess(pInfo.hProcess, 0);

Upvotes: 2

Related Questions