Creating the Windows child process and then executing the cmd command

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged.

To do: Creating Windows child process, executing cmd

To show: The various Windows Win32 CRT thread and process C functions

 

 

 

 

// For WinXp as a target

#define _WIN32_WINNT 0x0501

 

#include <windows.h>

#include <stdio.h>

 

int main(void)

{

STARTUPINFO si;

PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));

si.cb = sizeof(si);

ZeroMemory(&pi, sizeof(pi));

 

// Start the child process. If not OK...

if(!CreateProcess(L"C:\\WINDOWS\\system32\\cmd.exe", // module name.

NULL, // Command line.

NULL, // Process handle not inheritable.

NULL, // Thread handle not inheritable.

FALSE, // Set handle inheritance to FALSE.

0, // No creation flags.

NULL, // Use parent's environment block.

NULL, // Use parent's starting directory.

&si, // Pointer to STARTUPINFO structure.

&pi) // Pointer to PROCESS_INFORMATION structure.

)

 

// Then, give some prompt...

printf("\nSorry! CreateProcess() failed.\n\n");

// else, give some prompt...

else

{

printf("\nWell, CreateProcess() looks OK.\n");

printf("exit after 5000 ms...\n\n");

}

// Wait until child process exits after 5000 ms.

WaitForSingleObject(pi.hProcess, 5000);

printf("\n");

 

// Close process and thread handles. If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

// To get extended error information, call GetLastError().

if(CloseHandle(pi.hProcess) !=0)

printf("The process handle has been closed successfully\n");

if(CloseHandle(pi.hThread) != 0)

printf("The thread handle has been closed successfully\n");

return 0;

}

 

Output example:

 

Well, CreateProcess() looks OK.

exit after 5000 ms...

Microsoft Windows XP [Version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

f:\vc2005project\cplus\cplus>

The process handle has been closed successfully

The thread handle has been closed successfully

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index