[英]C# execute a terminal command in linux
我希望我的 c# 應用程序(我在樹莓派上執行)在啟動時運行 bash 腳本。
基本上:腳本位於/etc/init.d
中並命名為mnw
。 我希望每當我的 c# 應用程序啟動時,它應該執行 mnw 腳本的一部分。
如果它是在終端中編寫的,它看起來像:
cd /etc/init.d
./mnw stop
我希望這發生在public static void Main()
的開頭,我一直在嘗試
ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "/dev/init.d/./mnw", Arguments = "stop", };
Process proc = new Process() { StartInfo = startInfo, };
proc.Start();
但它說停止是一個意想不到的論點,有什么想法嗎?
在使用已接受的答案中的Process
class 時,我想補充一點,有一個名為CliWrap的庫可以使像這樣的 CLI 調用變得更加容易:
以 OPs 問題為例:
var result = await Cli
.Wrap("/dev/init.d/mnw")
.WithArguments("stop")
.ExecuteBufferedAsync();
// result contains:
// -- result.StandardOutput (string)
// -- result.StandardError (string)
// -- result.ExitCode (int)
// -- result.StartTime (DateTimeOffset)
// -- result.ExitTime (DateTimeOffset)
// -- result.RunTime (TimeSpan)
if (result.ExitCode != 0)
Console.WriteLine("Command failed")
感謝@Tyrrrz這個庫!
我從未在Mono / Linux上使用過ProcessStartInfo
,但是您是否嘗試過通過bash調用?
ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "/bin/bash", Arguments = "/dev/init.d/mnw stop", };
Process proc = new Process() { StartInfo = startInfo, };
proc.Start();
另外, mnw
上的可執行位沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.