how do i kill a process after say 2 or three minutes look at the following code:
class Program
{
static void Main(string[] args)
{
try
{
//declare new process and name it p1
Process p1 = Process.Start("iexplore", "http://www.google.com");
//get starting time of process
DateTime startingTime = p1.StartTime;
Console.WriteLine(startingTime);
//add a minute to startingTime
DateTime endTime = startingTime.AddMinutes(1);
//I don't know how to kill process after certain time
//code below don't work, How Do I kill this process after a minute or 2
p1.Kill(startingTime.AddMinutes(2));
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Problem with Process:{0}", ex.Message);
}
}
}
so I want that IE window closed after 2 minutes
Using the timeout Command. For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.
The difference between kill and terminate is that kill generally refers specifically to sending a signal, whereas terminate usually also includes other methods such as sending the process a command that tells it to exit (if the process includes a command interpreter of some kind).
Therfore, we can have such function to kill any process (if permissions allow you to) by PID. The process is killed before printing message on the console and therefore the answer is YES, a process can kill itself.
If it is a process group you want to kill, just use the kill(1) command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112 .
Use Process.WaitForExit
with a timeout of two minutes, and then call Process.Kill
if WaitForExit
returned false
.
(You might also to consider calling CloseMainWindow
instead of Kill
, depending on your situation - or at least try it first, to give the process more of a chance to do an orderly shutdown.)
Use a System.Threading.Timer and supply a TimerCallback (which contains your process.Kill) to be called back after 2 minutes. See the example here
//p1.Kill(startingTime.AddMinutes(2));
using (var timer = new Timer(delegate { p1.Kill(); }, null, 2000, Timeout.Infinite))
{
Console.ReadLine(); // do whatever
}
Edit: Jon's solution is simpler.. less types.. no Disposal reqd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With