Search code examples
asp.net-core.net-core

Why can't I execute commands in Linux terminal?


The framework I am using is .Net 8.

I tried to followed the accepted answer in How to execute Linux command line in C# Mono

And here is my code:

ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.FileName = "dmesg | grep tty";
_processStartInfo.UseShellExecute = false;
_processStartInfo.RedirectStandardOutput = true;
Process p = Process.Start(_processStartInfo );
var _result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();

After I ran the code, it reports this error:

Unhandled exception. System.ComponentModel.Win32Exception (2): An error occurred           trying to start process 'dmesg | grep tty' with working directory '/home/admin'          . No such file or directory
   at System.Diagnostics.Process.ForkAndExecProcess(ProcessStartInfo startInfo,           String resolvedFilename, String[] argv, String[] envp, String cwd, Boolean setCr          edentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32& stdinFd, Int32          & stdoutFd, Int32& stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)

In terminal of putty, the command runs well as below: enter image description here

What's wrong with it?


Solution

  • Try to use FileName and Arguments like below, it works in my side.

    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        FileName = "/bin/bash",
        Arguments = "-c \"dmesg | grep tty\"",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    };
    

    Here is the test result in my azure app service linux plateform.

    enter image description here