How can I check if CreateProcess is working or running? - c++

I use CreateProcess to start a .exe of mine. I want to know if everything worked fine or if it encouter errors when I tried to start this .exe.
From what I can tell, I need to use GetLastError(), but I tried to simulate an error in the process path but it return the same last error code.
So I want to catch if CreateProcess is successfull or not and if the process is done. What should I do to achieve that ?
Thanks.

All the information you are looking for is spelled out in the documentation for CreateProcess:
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.
Note that the function returns before the process has finished initialization. If a required DLL cannot be located or fails to initialize, the process is terminated. To get the termination status of a process, call GetExitCodeProcess.
If you need to wait for the target process to terminate, call WaitForSingleObject on the process handle returned in the PROCESS_INFORMATION filled out by the call to CreateProcess.
Since you control the target process, you are free to choose any scheme that allows you to determine success or failure from the process' exit code. You can call GetExitCodeProcess at any time after the process' handle transitioned to the signaled state, and before you call CloseHandle on it.

There are several approaches I can think of:
#1 - Enumeration
You can enumarate the processes and check if the PID is in the list. Check out EnumProcesses
#2 - Checking Exit Codes
You can use GetExitCodeProcess. It will return STILL_ACTIVE (259) if the process is still running
#3 - Process Handles
WaitForSingleObject uses a Process handle with the SYNCHRONIZE access right and returns 0 if the process is not running.
Note: You should not specify INFINITE for the dwMilliseconds parameter because the function would not return until the process state became signaled(process is terminated).

Related

OpenProcess vs CreateProcess

Can someone please explain to me what is the differance between:
OpenProcess and CreatProcess.
(I am trying to inject a DLL into a program and I dont know which one to use.)
OpenProcess is passed a process ID for an existing process, and returns a process handle for that process.
CreateProcess creates a brand new process, returning a handle to that new process (amongst other things).
If you want to inject into a process that is already running, then you will need OpenProcess.
In relation to injecting a .dll into another process,there are a couple of major benefits and differences between OpenProcess and CreateProcess.
The first is timing. You can inject the dll before the target process has had a chance to perform any of their own code by creating the process in a suspended state (dwCreationFlags with CREATE_SUSPENDED(0x00000004) set). Don't forget to resume the process once you are ready for it to execute.
The second is privilege. The process handle returned by CreateProcess automatically has PROCESS_ALL_ACCESS without the need to set SeDebugPrivilege first. OpenProcess does require your program to gain this privilege before it is allowed to use the PROCESS_ALL_ACCESS flag.
Some other minor things to remember:
CreateProcess cannot be called on a running process, but you can always call OpenProcess after CreateProcess if you needed to for whatever reason.
CreateProcess requires you to CloseHandle both the process and thread handles returned in PROCESS_INFORMATION, where OpenProcess only requires you to CloseHandle on it's return value (No thread handle gets opened).
If you need to change the Environment for whatever reason(unlikely), you'll have to use CreateProcess.
Further reading can be found:
CreateProcess
OpenProcess
process-security-and-access-rights

Using C++, How to detect process right before terminated

Im using Visual C++
I'm trying to monitor another process.
Is there a way to detect when the process is terminated ? I mean right before it's terminated, the program can raise an event. After that event, the process will be terminated.
I want my code run before the process is terminated.
The reason I want to do that because I use WMI to detect the process started. But some the process is ended too quickly, my code doesn't not run yet, but the process already ended.
You would use the DebugActiveProcess function, and then use a loop which starts with WaitForDebugEvent - when the process exits, you get a EXIT_PROCESS_DEBUG_EVENT.
You will probably get a bunch of other debug events [it depends on when you attach to the process and what the process does after that point]. For those, you will just issue a call to ContinueDebugEvent - if it was an exception, DBG_EXCEPTION_NOT_HANDLED should be used, otherwise, DBG_CONTINUE.
Once you see your EXIT_PROCESS_DEBUG_EVENT, you do your thing, then issue DBG_CONTINUE. You will also need to handle LOAD_DLL_DEBUG_EVENT by closing the handle given, or you'll leak handles.
I haven't used DebugActiveProcess in exactly this manner, but I believe this will work.
See these functions for more details:
Windows Debugging Functions

Is it possible to detect 'end process' externally?

Is there some way to detect that a program was ended by windows task manager's "end process"?
I know that its kinda impossible to do that from within the application being ended (other than to build your app as a driver and hook ZwTerminateProcess), but I wonder if there is a way to notice it from outside.
I don't want to stop the program from terminating, just to know that it was ended by "end process" (and not by any other way).
There might be a better way - but how about using a simple flag?
Naturally, you'd have to persist this flag somewhere outside of the process/program's memory - like the registry, database, or file system. Essentially, when the app starts up, you set the flag to 'True' when the app shuts down through the normal means, you set the flag to 'False'.
Each time the application starts you can check the flag to see if it was not shut down correctly the previous time it was executed.
Open up a handle to the process with OpenProcess, and then wait on that handle using one of the wait functions such as WaitForSingleObject. You can get the exit status of the process using GetExitCodeProcess. If you need your program to remain responsive to user input while waiting, then make sure to wait on a separate thread (or you can periodically poll using a timeout of zero, but remember the performance consequences of polling -- not recommended).
When you're done, don't forget to call CloseHandle. The process object won't be fully deleted from the OS until all of its handles are closed, so you'll leak resources if you forget to call CloseHandle.
Note that there's no way to distinguish between a process exiting normally or being terminated forcefully. Even if you have a convention that your program only ever exits with a status of 0 (success) or 1 (failure) normally, some other process could call TerminateProcess(YourProcess, 1), and that would be indistinguishable from your ordinary failure mode.
According to the documentation, ExitProcess calls the entry point of all loaded DLLs with DLL_PROCESS_DETACH, whereas TerminateProcess does not. (Exiting the main function results in a call to ExitProcess, as do most unhandled exceptions.)
You might also want to look into Application Recovery and Restart.
One option might be to create a "watchdog" application (installed as a service, perhaps) that monitors WMI events for stopping a process via the ManagementEventWatcher class (in the System.Management namespace).
You could query for the death of your process on an interval or come up with some event driven way to alert of your process's demise.
Here's sort of an example (it's in C# though) that could get you started.

Get Thread exit code after running ShellExecuteEx

How can the exit code of the main thread be retrieved, after having run ShellExecuteEx() in asychronous mode?
The process exit code can simply be retrieved as follows:
SHELLEXECUTEINFO execInfo;
execInfo.cbSize = sizeof(SHELLEXECUTEINFO);
execInfo.fMask = SEE_MASK_NOASYNC;
ShellExecuteEx(&execInfo);
/* Get process exit code. */
DWORD processExitCode;
GetExitCodeProcess(execInfo.hProcess, &processExitCode);
But how can the exit code of the main thread be retrieved? What should be passed to GetExitCodeThread()?
The exit code of the main thread is equal to the exit code of the process IMHO.
In order to get the exit code of the primary process thread - one has to obtain its HANDLE. Unfortunately ShellExecuteEx doesn't return you this (it returns only the HANDLE of the newly created process).
One could also enumerate all the threads in a particular process and open their handles (OpenThread). Thus, you could create a process in a "suspended" state, get the handle of its only thread (which didn't start execution yet), and then go on.
Alas, ShellExecuteEx neither allows you to create a new process in a suspended state.
So that I don't see a clean way to achieve what you want. I'd suggest the following:
Why would you want the exit code of the primary thread anyway? Perhaps the exit code of the process will be enough?
Consider using CreateProcess. It has the needed functionality.
Some dirty tricks may help, like injecting DLLs into the newly created process (hooking) and etc.

Prossess state getting in c under window plateform

I am using CreateProcess function for creating the process, is there any option to get the current state of the process (running or not). Kindly guide me how can I make it possible.
Use OpenProcess function with that dwProcessId if it returns NULL Process is not running otherwise it will return handle to that process
Create process returns a handle to the process in PROCESS_INFORMATION structure, you can use this with something like GetExitCodeProcess to work out if it is still running, or you can use the wait functions to wait for it to exit.