Using CreateProcess in console app

Flaviu_ 1,031 Reputation points
2022-11-23T10:35:47.643+00:00

I have the following code:

int main(int argc, char* argv[])  
{  
	std::string cmdLine("cmd ipconfig /all");  
  
	std::cout << "Begin command ...\n";  
  
	STARTUPINFO si;  
	PROCESS_INFORMATION pi;  
  
	ZeroMemory(&si, sizeof(si));  
	si.cb = sizeof(si);  
	ZeroMemory(&pi, sizeof(pi));  
  
	BOOL bSuccess = ::CreateProcess(NULL,   
									CA2W(cmdLine.c_str()),  
									NULL,  
									NULL,  
									FALSE,  
									NORMAL_PRIORITY_CLASS,  
									NULL,  
									NULL,  
									&si,  
									&pi);  
  
	if (! bSuccess)  
		return 0;  
  
	std::cout << "Wait command ...\n";  
	WaitForSingleObject(pi.hProcess, INFINITE);  
	::CloseHandle(pi.hThread);  
	// Close the process handle as soon as it is no longer needed.  
	::CloseHandle(pi.hProcess);  
	std::cout << "Command ended.\n";  
	return 0;  
}  

So, if I run this app, from command line window:

263230-image.png

So, looks like never reach Command ended point, seems like WaitForSingleObject is block the program flow. If I remove WaitForSingleObject call, the app will show it will be reach end of the program:

263405-image.png

But, I need to know when the my command, in this test case, ipconf /all is done, so, I really need this WaitForSingleObject call. I have took this code from here: https://learn.microsoft.com/en-us/windows/win32/procthread/creating-processes

Developer technologies C++
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2022-11-23T10:59:18.417+00:00

    You forgot /C :

    std::string cmdLine("cmd /C ipconfig /all");  
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Flaviu_ 1,031 Reputation points
    2022-11-23T10:59:43.043+00:00

    Yes, it goes now, when I removed cmd word from command. Thanks.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.