Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen For Process Start and End

I'm new to Windows API programming. I am aware that there are ways to check if a process is already running (via enumeration). However, I was wondering if there was a way to listen for when a process starts and ends (for example, notepad.exe) and then perform some action when the starting or ending of that process has been detected. I assume that one could run a continuous enumeration and check loop for every marginal unit of time, but I was wondering if there was a cleaner solution.

like image 872
John Roberts Avatar asked Aug 18 '12 14:08

John Roberts


3 Answers

Use WMI, Win32_ProcessStartTrace and Win32_ProcessStopTrace classes. Sample C# code is here.

You'll need to write the equivalent C++ code. Which, erm, isn't quite that compact. It's mostly boilerplate, the survival guide is available here.

like image 132
Hans Passant Avatar answered Oct 05 '22 12:10

Hans Passant


If you can run code in kernel, check Detecting Windows NT/2K process execution.

like image 43
Sheng Jiang 蒋晟 Avatar answered Oct 05 '22 13:10

Sheng Jiang 蒋晟


Hans Passant has probably given you the best answer, but... It is slow and fairly heavy-weight to write in C or C++.

On versions of Windows less than or equal to Vista, you can get 95ish% coverage with a Windows WH_CBT hook, which can be set with SetWindowsHookEx.

There are a few problems:

  1. This misses some service starts/stops which you can mitigate by keeping a list of running procs and occasionally scanning the list for changes. You do not have to keep procs in this list that have explorer.exe as a parent/grandparent process. Christian Steiber's proc handle idea is good for managing the removal of procs from the table.

  2. It misses things executed directly by the kernel. This can be mitigated the same way as #1.

  3. There are misbehaved apps that do not follow the hook system rules which can cause your app to miss notifications. Again, this can be mitigated by keeping a process table.

The positives are it is pretty lightweight and easy to write.

For Windows 7 and up, look at SetWinEventHook. I have not written the code to cover Win7 so I have no comments.

like image 35
JimR Avatar answered Oct 05 '22 12:10

JimR