private static void WatchOutputStream() { while (!ThatProgramProcess.StandardOutput.EndOfStream) { OutputStringBuilder.AppendLine(ThatProgramProcess.StandardOutput.ReadLine()); //检测OLE if (OutputStringBuilder.Length > OutputLimit) { //强制结束进程 try { ThatProgramProcess.Kill(); } catch (Exception) { } StatusCode = Const.StatusCodeOutputLimitExceeded; break; } } }
private static void WatchTimeAndMemory() { bool cpuIdleFlag = false; long cpuIdleStartTime = 0; long lastUsedTime = 0; while (!ThatProgramProcess.HasExited) { try { UsedTime = Convert.ToInt64(ThatProgramProcess.TotalProcessorTime.TotalMilliseconds); UsedMemory = Convert.ToInt64(ThatProgramProcess.PeakWorkingSet64); //检测是否挂起 if (UsedTime != lastUsedTime) { cpuIdleFlag = false; cpuIdleStartTime = 0; lastUsedTime = UsedTime; } else { if (cpuIdleFlag == false) { cpuIdleFlag = true; cpuIdleStartTime = DateTime.Now.Ticks; } if ((DateTime.Now.Ticks - cpuIdleStartTime) / 10 / 1000 / 1000 == 10) { //CPU空闲超过10秒,强制TLE UsedTime = TimeLimit; } } //检测TLE if (UsedTime >= TimeLimit) { //强制结束进程 try { ThatProgramProcess.Kill(); } catch (Exception) { } StatusCode = Const.StatusCodeTimeLimitExceeded; break; } //检测MLE if (UsedMemory >= MemoryLimit) { //强制结束进程 try { ThatProgramProcess.Kill(); } catch (Exception) { } StatusCode = Const.StatusCodeMemoryLimitExceeded; break; } } catch (InvalidOperationException) { break; } } }