Files
Electron.NET/ElectronNET.CLI/ProcessHelper.cs

86 lines
2.6 KiB
C#
Raw Normal View History

2017-10-05 21:28:47 +02:00
using System;
using System.Collections.Concurrent;
2017-10-05 21:28:47 +02:00
using System.Diagnostics;
2017-10-08 23:22:20 +02:00
using System.Runtime.InteropServices;
2017-10-05 21:28:47 +02:00
namespace ElectronNET.CLI
{
public class ProcessHelper
{
2021-09-15 11:14:45 +02:00
private static readonly ConcurrentDictionary<Process, bool> _activeProcess = new();
public static void KillActive()
{
foreach(var kv in _activeProcess)
{
if (!kv.Key.HasExited)
{
try
{
kv.Key.CloseMainWindow();
}
catch
{
}
try
{
2021-08-25 09:54:00 +02:00
kv.Key.Kill(true);
}
catch
{
}
}
}
}
public static int CmdExecute(string command, string workingDirectoryPath, bool output = true, bool waitForExit = true)
2017-10-05 21:28:47 +02:00
{
using (Process cmd = new Process())
{
2017-10-08 23:22:20 +02:00
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
{
2021-04-29 08:29:36 +05:00
cmd.StartInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
2017-10-08 23:22:20 +02:00
}
else
{
2017-10-11 23:29:58 +02:00
// works for OSX and Linux (at least on Ubuntu)
2021-04-29 21:11:16 +05:00
var escapedArgs = command.Replace("\"", "\\\"");
cmd.StartInfo = new ProcessStartInfo("bash", $"-c \"{escapedArgs}\"");
2017-10-08 23:22:20 +02:00
}
2017-10-05 21:28:47 +02:00
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
2017-10-05 21:28:47 +02:00
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = workingDirectoryPath;
if (output)
{
2021-04-29 08:29:36 +05:00
cmd.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
cmd.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
}
2017-10-05 21:28:47 +02:00
2021-04-29 21:25:42 +05:00
Console.WriteLine(command);
2017-10-05 21:28:47 +02:00
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
2017-10-05 21:28:47 +02:00
if (waitForExit)
{
_activeProcess[cmd] = true;
cmd.WaitForExit();
_activeProcess.TryRemove(cmd, out _);
}
2021-04-29 08:29:36 +05:00
return cmd.ExitCode;
2017-10-05 21:28:47 +02:00
}
}
}
}