forked from ElectronNET/Electron.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessHelper.cs
More file actions
75 lines (65 loc) · 2.28 KB
/
Copy pathProcessHelper.cs
File metadata and controls
75 lines (65 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace ElectronNET.CLI
{
public class ProcessHelper
{
private static ConcurrentDictionary<Process, bool> _activeProcess = new();
public static void KillActive()
{
foreach (var kv in _activeProcess.Where(p => !p.Key.HasExited))
{
try
{
kv.Key.CloseMainWindow();
}
catch { /* Do not crash */ }
try
{
kv.Key.Kill(true);
}
catch { /* Do not crash */ }
}
}
public static int CmdExecute(string command, string workingDirectoryPath, bool output = true, bool waitForExit = true)
{
using Process cmd = new();
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
{
cmd.StartInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
}
else
{
// works for OSX and Linux (at least on Ubuntu)
var escapedArgs = command.Replace("\"", "\\\"");
cmd.StartInfo = new ProcessStartInfo("bash", $"-c \"{escapedArgs}\"");
}
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = workingDirectoryPath;
if (output)
{
cmd.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
cmd.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
}
Console.WriteLine(command);
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
if (waitForExit)
{
_activeProcess[cmd] = true;
cmd.WaitForExit();
_activeProcess.TryRemove(cmd, out _);
}
return cmd.ExitCode;
}
}
}