p
关闭后
WaitForExit()
,导致
p.StandardError
无法进入。
所以我们可以像下面这样修改代码。
public async Task<IActionResult> Syslog(string param = "-r -u eevatest.service --since \"2 days ago\"")
{
var p = new Process
{
StartInfo = {
FileName = "/usr/bin/journalctl",
Arguments = param,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
try
{
p.Start();
Task<string> errorTask = p.StandardError.ReadToEndAsync();
Task<byte[]> outputTask = ReadStreamAsync(p.StandardOutput.BaseStream);
bool exited = await Task.Run(() => p.WaitForExit(60000));
if (!exited)
throw new Exception("journalctl did not exit in time");
string errorOutput = await errorTask;
byte[] output = await outputTask;
if (p.ExitCode != 0)
throw new Exception($"journalctl exited with code {p.ExitCode}, error: {errorOutput}");
return new ContentResult { Content = Encoding.UTF8.GetString(output) };
}
finally
{
p.Dispose();
}
}
private static async Task<byte[]> ReadStreamAsync(Stream stream)
{
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
return ms.ToArray();
}
它对我有效。