I have a C# program that compiles and executes a C++ program. Sometimes, if there are infinite loops during runtime, the process gets into a linux D mode which means that it is not responding to anything because it's waiting for an internal event (I/O).
To write to the C++ program I have redirected the Input and Output stream accordingly.
if (input.Trim () != "") {
proc.StandardInput.WriteLine (input);
}
try{
output = proc.StandardOutput.ReadToEnd ();
}
catch{
output = "Runtime > 500ms .";
}
A timer checks if the process lasts longer than 500 ms and tries to dispose it if so. Otherwise, it kills it.
timer.Elapsed += delegate {
try{
try{
proc.StandardOutput.Close();
proc.StandardInput.Close();
}catch{}
try{
proc.Kill();
proc.Dispose();
}catch{}
timer.Enabled = false;
Log.Warn("A process took longer than expected. Streams and objects were disposed.");
}
catch(Exception e){Log.ErrorTrace("Timer " + e.ToString());}
};
Although this method works most of the time, when the server is filled with requests for running programs with infinite runtime orphan processes start to appear and eat up resources.
The program runs as root hence the possibility of lacking permissions is null.
Is this the right way to dispose Processes which imply running non-responding tasks on a linux machine?
Please note:
- that the requests are made via sockets, therefore timing is crucial.
- that killing the processes manually via pid will fail (see D mode)