/// <summary> /// Finds PIDs by using `ps -lef` command /// </summary> /// <param name="commandToFind">Command looking for in CMD column</param> /// <returns>List of PIDs, matches to commands find in CMD column</returns> public static List <int> FindPIDs(string commandToFind) { List <int> PIDs = new List <int>(); string psCommand = "ps -lef"; BashProcess psProcess = new BashProcess(psCommand) { SubscribeStandardOutput = false }; string psResult = psProcess.RunNewProcessAndReadStdOutput(); commandToFind = Regex.Escape(commandToFind); Regex pidRegex = new Regex($@"[0-9] [A-Z] \w+\s+(\d+).* {commandToFind}"); MatchCollection pidMatches = pidRegex.Matches(psResult); if (pidMatches.Count > 0) { foreach (Match match in pidMatches) { if (match.Groups?.Count > 1) { string pid = match.Groups[1].Value; if (int.TryParse(pid, out int foundPid)) { PIDs.Add(foundPid); } } } } return(PIDs); }
/// <summary> /// Kill process by PID /// </summary> /// <param name="pid">Process ID</param> /// <returns>True if process has been started succesfully, false if not.</returns> public static bool KillProcess(int pid, BashProcessKillSignals signalNumber = BashProcessKillSignals.SIGTERM) { BashProcess killer = new BashProcess($"kill -{(int)signalNumber} {pid}"); return(killer.RunNewProcessAndWaitForFinish()); }