首页 > 解决方案 > 无法使用 C# 中的 Process 类获取有关在 bash 中运行的命令的信息

问题描述

我在 Linux 上的 azure app 服务中部署了 ASP.NET 核心 MVC 应用程序。当我尝试运行 /bin/bash 并执行一些脚本时,例如:dotnet run test.dll 或 javac Test.java,当我尝试获取有关已退出进程的一些信息(如 MemotyUsed 和 TimeUsed)时,我收到以下错误:“无法检索有关进程或线程的指定信息。它可能已退出或可能具有特权“

当我在 Windows 上运行该应用程序时,一切正常。我还尝试在 linux os 上的 docker 中运行该应用程序,因为我认为问题来自 azure app 服务。但是,在 docker 容器中再次引发了相同的错误。所以我认为这个问题来自linux os。

ProcessExecutionResult processExecutionResult = new ProcessExecutionResult();

using (Process process = new Process())
{
    process.StartInfo.FileName = "/bin/bash";
    process.StartInfo.Arguments = arguments;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.UseShellExecute = false;

    process.Start();

    if (!string.IsNullOrEmpty(input))
    {
        await process.StandardInput.WriteLineAsync(input);
        await process.StandardInput.FlushAsync();
        process.StandardInput.Close();
    }

    bool exited = process.WaitForExit(ProcessMaxRunningTime);

    if (!exited)
    {
        process.Kill();
        processExecutionResult.Type = ProcessExecutionResultType.TimeLimit;
    }

    string output = await process.StandardOutput.ReadToEndAsync();
    string errors = await process.StandardError.ReadToEndAsync();

    processExecutionResult.ErrorOutput = errors;
    processExecutionResult.ReceivedOutput = output;
    processExecutionResult.ExitCode = process.ExitCode;
    processExecutionResult.TimeWorked = process.ExitTime - process.StartTime;
    processExecutionResult.PrivilegedProcessorTime = process.PrivilegedProcessorTime;
    processExecutionResult.UserProcessorTime = process.UserProcessorTime;
}

当我尝试访问process.ExitTimeprocess.StartTime或有关进程的一些其他信息时出现错误:无法检索有关进程或线程的指定信息。它可能已经退出或可能被特权抛出。

标签: c#linuxbashasp.net-coreazure-web-app-service

解决方案


推荐阅读