1
|
using System.Diagnostics;
|
2
|
|
3
|
namespace LDClient.detection;
|
4
|
|
5
|
/// <summary>
|
6
|
/// This class implements the IProcessUtils interface.
|
7
|
/// It implements methods that are used when dealing with processes.
|
8
|
/// </summary>
|
9
|
public class ProcessUtils : IProcessUtils {
|
10
|
|
11
|
/// <summary>
|
12
|
/// Checks if a process is running or not.
|
13
|
/// </summary>
|
14
|
/// <param name="name">Name of the process</param>
|
15
|
/// <returns>True, if the process is running. False otherwise.</returns>
|
16
|
public bool IsProcessRunning(string name) {
|
17
|
return Process.GetProcessesByName(name).Length > 0;
|
18
|
}
|
19
|
|
20
|
/// <summary>
|
21
|
/// Executes a new process (t32rem.exe) with arguments which are passed in
|
22
|
/// as a parameter of the method.
|
23
|
/// </summary>
|
24
|
/// <param name="fileName">Path to the .exe file</param>
|
25
|
/// <param name="argument">Arguments passed into the .exe file</param>
|
26
|
/// <param name="timeout">Timeout used when waiting for the process to terminate</param>
|
27
|
/// <param name="desiredExitCode">Status code indicating a successful termination of the process.</param>
|
28
|
/// <returns>True, if the command was executed successfully. False otherwise.</returns>
|
29
|
public bool ExecuteNewProcess(string fileName, string argument, int timeout, int desiredExitCode) {
|
30
|
// Create a new process.
|
31
|
var t32RemProcess = new Process();
|
32
|
t32RemProcess.StartInfo.FileName = fileName;
|
33
|
t32RemProcess.StartInfo.Arguments = argument;
|
34
|
|
35
|
try {
|
36
|
// Execute the process and wait until it terminates or until the timeout is up.
|
37
|
t32RemProcess.Start();
|
38
|
if (!t32RemProcess.WaitForExit(timeout)) {
|
39
|
Program.DefaultLogger.Error($"Execution has not terminated within a predefined timeout of {timeout} ms");
|
40
|
return false;
|
41
|
}
|
42
|
|
43
|
// Check if the process terminated successfully.
|
44
|
if (t32RemProcess.ExitCode != desiredExitCode) {
|
45
|
Program.DefaultLogger.Error($"Execution terminated with an error code of {t32RemProcess.ExitCode}");
|
46
|
return false;
|
47
|
}
|
48
|
} catch (Exception exception) {
|
49
|
Program.DefaultLogger.Error($"Failed to run {fileName} {argument}. {exception.Message}");
|
50
|
return false;
|
51
|
}
|
52
|
return true;
|
53
|
}
|
54
|
}
|