简体   繁体   中英

Naming a Process so i can kill it later on

I have a Process I start off that will ping a host repeatedly using:

ping my_ip /t

I use this code to start it

Process process = new Process();
process.StartInfo = new ProcessStartInfo(@"C:\windows\system32\cmd.exe");
process.StartInfo.UseShellExecute = false; 
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Arguments = "/c ping " + my_ip  + " /t";
process.Start();

Now, if my app is terminated unexpectedly i would like to close this 'PING' on restarting the app.

I could enumerate through the processes until I see the name 'ping' and kill it.

But being a pessimistic programmer there might be another Ping process started by another app so I would not want to kill that process.

is there a way to set the id of a process so that I can kill that process specifically?

i am using C#

You don't have to name it. You have it already in the process variable. Just store this somewhere, then call:

process.Kill();

Whenever you are exiting your application

PS: Notice that you are using process.WaitForExit(); this will block your application till the secondary process ends. Don't know why you have it there.

Update

As per the comments, you say that you may want to kill the process if your application is terminated unexpectedly.

Two things:

1) If your application is terminated in a non-deterministic way (fatal crash or something like that), then there's nothing you can do on your application's shutdown, thus you couldn't terminate the process even if it had a name.

2) Your Process variable has an Id field. You could store this on disk or something and try to kill it upon application re-startup. A warning though: processes id's are not exclusive... if your spawned ping has terminated (by any means), other process could have taken the same id. You can only be sure it was your original spawned process if you are controlling that process' termination.

As a possible solution to this, you can create a "Job Object" ( documentation ) using JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE for its limit ( doc ), and assign the child process to it using AssignProcessToJobObject , which would be make the child process by killed by Windows when your process terminates.

I don't think there's a .NET wrapper for Job Objects (I don't know of one), so it should take some P/Invoking and defining the structures, but it could be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM