rockstar
rockstar

Reputation: 3538

How to make a process send notification upon its termination

I wanted to programatically determine when a process has terminated. I searched in various forums and came across the PsSetCreateProcessNotifyRoutine routine.

Also, I came across a similar StackOverflow question:

.NET Events for Process executable start.

In the accepted answer I see a query that I can possibly use. I am however unable to quite comprehend the query.

Can someone suggest a way I can implement my solution?

Upvotes: 2

Views: 220

Answers (2)

JeffRSon
JeffRSon

Reputation: 11216

Either you start the process yourself or find it by enumerating Process.GetProcesses() or calling Process.GetProcessesByName(...).

In any case you'll have some process handle p. Now you can subcribe to its Exited event or wait by p.WaitForExit().

This answer is based on your C# tag. However, with PowerShell it'll work like that too. Just the syntax may change. So you'll need to explore PowerShell's Process API (Start-Process and alike).

Upvotes: 3

oleksii
oleksii

Reputation: 35925

Basically, you need to hook to Windows Management API, which allows you to listen to started and stopped processes. Once WMI send notification to your program you will get control inside the either of (based on the answer)

private void ProcessEnded(object sender, EventArrivedEventArgs e)
private void ProcessStarted(object sender, EventArrivedEventArgs e)

From the arguments you will be able to get the process name.

This is how you receive a notification in managed code. Now the next step would be to send this notification to your script, and depending what it is you can use inter-process communication with WCF, a RESTfull call, run a script with parameters etc.

Upvotes: 3

Related Questions