MyExec, calls CreateProcess, waits for completion. WinBase


/ Published in: C++
Save to your folder(s)

I occasionally need a WinExec function the synchronously executes a command. cwdArg may be null.

This example, upon error, pops-up a dialog and exits the app. This is useful for small installation utilities.

non-dot.net, with or without MFC.


Copy this code and paste it in your HTML
  1. static void MyExec( LPCSTR cmdArg, LPCSTR cwdArg )
  2. {
  3. STARTUPINFO si = {sizeof(STARTUPINFO)};
  4. PROCESS_INFORMATION pi = {0};
  5.  
  6. BOOL bOk = CreateProcess(
  7. NULL, // No module name (use command line)
  8. (LPSTR)cmdArg, // Command line
  9. NULL, // Process handle not inheritable
  10. NULL, // Thread handle not inheritable
  11. FALSE, // Set handle inheritance to FALSE
  12. 0, // No creation flags
  13. NULL, // Use parent's environment block
  14. (LPSTR)cwdArg, // Use parent's starting directory
  15. &si, // Pointer to STARTUPINFO structure
  16. &pi // Pointer to PROCESS_INFORMATION structure
  17. );
  18.  
  19. // Wait until child process exits.
  20. WaitForSingleObject( pi.hProcess, INFINITE );
  21.  
  22. // Close process and thread handles.
  23. CloseHandle( pi.hProcess );
  24. CloseHandle( pi.hThread );
  25.  
  26. if ( bOk ) { return; }
  27.  
  28. CString s;
  29. s.Format( "Unable to execute '%s'", cmdArg );
  30. MessageBox( NULL, s, APP_NAME, 0 );
  31. exit(-1);
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.