C# Monitor Programs Periodically Based on PID
Thank you in advance for you ideas and input.
I would like to periodically check to see if a third party program is currently running on a user's system from my program. I am currently launching the program as follows in C#:
String plinkConString = ""; // my connection string
Process plink = Process.Start(utilityPath + @"\putty.exe", plinkConString);
int plinkProcessId = plink.Id;
I launch the program and grab its pid in a Windows environment. As Put开发者_运维百科ty/PLink may disconnect from its SSH server at some point and close, what is the best way to monitor how this process is doing in code?
Is there a better way to launch this program to monitor its success or failure?
If you want to check whether the process is still up and running you can check the HasExited
property:
Process plink = Process.Start(utilityPath + @"\putty.exe", plinkConString);
....
bool isRunning = plink.HasExited;
The following code would check whether putty is running. It works also, if the program has been started by the user:
bool isRunning = Process.GetProcessesByName("putty").Length > 0;
You can use Process.WaitForExit()
or Process.WaitForExit(int)
, or use the Process.Exited
event handler. You may also be interested in Monitor
if you want any more complex behaviour than that.
精彩评论