private static bool CloseHandle(RestartManager.RM_PROCESS_INFO locker, DetectOpenFiles.HandleRecord[] handles, string path) { foreach (var handle in handles) { try { handle.Close(); } catch (Exception ex) { Log.Verbose($"Error while closing handle {ex}"); return false; } } return Wait(handles); }
private static Result Liberate(RestartManager.RM_PROCESS_INFO locker, string path) { var process = Process.GetProcessById(locker.Process.dwProcessId); var handles = DetectOpenFiles.GetOpenFilesEnumerator(process.Id).Where(h => h.FilePath.StartsWith(path, StringComparison.CurrentCultureIgnoreCase)).ToArray(); /*Need to access these variables after the process is terminated.*/ var processId = process.Id; var processName = process.ProcessName; if (Can(Result.ServiceStop) && StopService(locker, handles)) { Log.Info($"Stopped windows service {locker.strServiceShortName} ({locker.strAppName}) with id {processId}."); return Result.Message; } if (Can(Result.Message) && SendCloseMessage(process, handles)) { Log.Info($"Closed {processName} with id {processId} via close message."); return Result.Message; } if(Can(Result.CloseHandle) && CloseHandle(locker, handles, path)) { Log.Info($"Closed {handles.Length} handle(s) in process {processName} with id {processId}."); return Result.CloseHandle; } if (Can(Result.Kill) && Kill(process)) { Log.Info($"Killed {processName} with id {processId}."); return Result.Kill; } return Result.Failure; }
private static bool StopService(RestartManager.RM_PROCESS_INFO locker, DetectOpenFiles.HandleRecord[] handles) { if (!string.IsNullOrEmpty(locker.strServiceShortName)) { Log.Verbose($"Found windows service {locker.strServiceShortName}"); var service = new ServiceController(locker.strServiceShortName); service.Stop(); try { return Wait(handles); } catch(Exception ex) { Log.Error($"Service {locker.strServiceShortName} failed to stop:" + ex.Message); return false; } } return false; }