I have a method to start process from my c# code in dotnet core 2. This method is like following:
internal static string[] RunCommand(string filename, string args, string workingDirectory = null)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
//WindowStyle = ProcessWindowStyle.Hidden
}
};
if (workingDirectory != null)
{
proc.StartInfo.WorkingDirectory = workingDirectory;
}
//Console.WriteLine(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
List<string> lines = new List<string>();
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
lines.Add(line);
}
}
proc.Dispose();
return lines.ToArray();
}
The problem is that some started processes fall in a loop and it make my vps run into problem.
So the question is that is there any solution to run a process with deadline?
Update
According to the recommendation of 'Jacek Blaszczynski' I have tried the code bellow:
internal static string[] RunCommand(string filename, string args, string workingDirectory = null, int timeoutInSeconds = 60)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
//WindowStyle = ProcessWindowStyle.Hidden
}
};
if (workingDirectory != null)
{
proc.StartInfo.WorkingDirectory = workingDirectory;
}
//Console.WriteLine(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
List<string> lines = new List<string>();
bool isKilled = false;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Thread.Sleep(timeoutInSeconds * 1000);
try
{
if (proc != null && !proc.HasExited)
{
isKilled = true;
proc.Kill();
Console.WriteLine("Annoying process killed.");
}
}
catch
{
// just let it go
}
}).Start();
try
{
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
lines.Add(line);
}
}
proc.Dispose();
}
catch
{
// just look what happens
}
return isKilled ? new string[] { "" } : lines.ToArray();
}
But still I have some wander processes. As debugging of multi thread processes are very hard and the case that causes this situation is unknown to me, Do you have any idea why should some process get out live of my trap?