Shilpi Boosar Says:
So today i do this but when i execute it that my application hangs and when i checked it on task mgr than its status is not responding.
The reason it hangs is because you are making the main thread wait for the other process to finish. The main thread is responsible for processing messages sent from windows, hence the messages are not reaching your application (worse, you are deleting them).
What you need to do is create a second thread which will do all the executing and waiting, while the main thread continues to handle the message pump. You can then use something like an
event[
^] or a PostMessage to notify the main thread that something has happened.
If you are using a GUI program, which it seems you are, then I would reccomend using PostMessage.
It is unclear weather you are using MFC, Win32 API or some other GUI library, so I will post the code for a console program
#include <StdIO.h>
#include <tchar.h>
#include <Windows.h>
#define CM_WAITED WM_APP //This is if you use SendMessage/PostMessage. Add this to your message handler.
DWORD g_nRetVal = 0;
DWORD g_nWaitCode = 0;
HANDLE g_hWaited = NULL;
DWORD WINAPI RunUtils(void *pParam) {
LPCTSTR szExe = TEXT("C:\\WINDOWS\\system32\\cleanmgr.exe");
LPTSTR szParams = TEXT(" /d C:");
PROCESS_INFORMATION ProcessInfo;
ZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
STARTUPINFO StartupInfo;
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
StartupInfo.cb = sizeof(StartupInfo);
StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow = SW_HIDE;
if (CreateProcess(szExe, szParams, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &StartupInfo, &ProcessInfo)) {
g_nWaitCode = WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
switch (g_nWaitCode) {
case WAIT_OBJECT_0:
GetExitCodeProcess(ProcessInfo.hProcess, &g_nRetVal);
break;
case WAIT_FAILED:
g_nWaitCode = GetLastError();
break;
}
::CloseHandle(ProcessInfo.hProcess);
::CloseHandle(ProcessInfo.hThread);
SetEvent(g_hWaited);
}
return 0;
}
int main() {
g_hWaited = CreateEvent(NULL, FALSE, FALSE, TEXT("Local\\WaitedEvent"));
HANDLE hExecThread = CreateThread(NULL, 0, &RunUtils, NULL, 0, NULL);
DWORD nLoops = 0;
for (;;) {
if (WaitForSingleObject(g_hWaited, 0) == WAIT_OBJECT_0) {
if (g_nWaitCode == WAIT_OBJECT_0) {
_tprintf(TEXT("Process completed successfully and returned %u\n"), g_nRetVal);
} else {
_tprintf(TEXT("Wait failed with error code %u\n"), g_nWaitCode);
}
break;
}
_tprintf("%u\n", ++nLoops);
Sleep(1000);
}
return 0;
}