summaryrefslogtreecommitdiff
path: root/src/marlin.agents.shell/CommandRunner.cs
diff options
context:
space:
mode:
Diffstat (limited to 'src/marlin.agents.shell/CommandRunner.cs')
-rw-r--r--src/marlin.agents.shell/CommandRunner.cs38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/marlin.agents.shell/CommandRunner.cs b/src/marlin.agents.shell/CommandRunner.cs
new file mode 100644
index 0000000..d4fcbb3
--- /dev/null
+++ b/src/marlin.agents.shell/CommandRunner.cs
@@ -0,0 +1,38 @@
+using System.Diagnostics;
+
+public static class CommandRunner
+{
+ public static async Task<int> RunAsync(string command, Action<string> onStdout, Action<string> onStderr)
+ {
+ var psi = new ProcessStartInfo
+ {
+ FileName = GetShell(),
+ RedirectStandardInput = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true
+ };
+
+ var process = new Process { StartInfo = psi };
+ process.OutputDataReceived += (_, e) => { if (e.Data != null) onStdout(e.Data); };
+ process.ErrorDataReceived += (_, e) => { if (e.Data != null) onStderr(e.Data); };
+
+ process.Start();
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ // Write the command to stdin and close it
+ await process.StandardInput.WriteLineAsync(command);
+ await process.StandardInput.WriteLineAsync("exit $?"); // Exit with the command's exit code
+ process.StandardInput.Close();
+
+ await process.WaitForExitAsync();
+ return process.ExitCode;
+ }
+
+ private static string GetShell()
+ {
+ return OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/bash";
+ }
+} \ No newline at end of file