c# - C# Process.StandardOutput.ReadLine() 挂起
问题描述
所以基本上 ReadLine() 方法只是挂在最后一个输出行上。
我不需要结束这个过程。主要目标是使用标准输入和标准输出(在变量/打印输出中)执行“cmd-shell”。
如果异步方法也能达到同样的效果,请在评论中留下。提前致谢。
{
Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd")
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
Arguments = "/K",
}
};
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
};
p.Start();
while (true)
{
Console.Write("/SHELL/ #> ");
input = Console.ReadLine();
p.StandardInput.WriteLine(input);
p.BeginErrorReadLine();
Console.WriteLine("Errorgoing...");
while (p.StandardOutput.Peek() > -1) {
Console.WriteLine(p.StandardOutput.Peek());
Console.WriteLine(p.StandardOutput.ReadLine());
// When it hangs, Peek() outputs 67, that represents "C" char.
// Seems like just the last stdout line dont want to be printed out.
}
}
}
}```
解决方案
在实施了一些技巧之后,我最终得到了以下代码。相当棘手。
static async Task Main(string[] args)
{
using (SemaphoreSlim semaphore = new SemaphoreSlim(0, 1))
{
Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd")
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
Arguments = "/K set PROMPT=PROMPT$P$G$_",
}
};
p.ErrorDataReceived += (s, e) =>
{
if (e.Data?.Length > 0)
{
Console.WriteLine(e.Data);
}
};
bool wasprompt = false;
string prompt = "";
p.OutputDataReceived += (s, e) =>
{
if (e.Data?.Length > 0)
{
if (e.Data.StartsWith("PROMPT") && e.Data.EndsWith(">"))
{
prompt = e.Data.Substring(6, e.Data.Length - 7);
semaphore.Release();
wasprompt = true;
}
else
{
if (!wasprompt)
Console.WriteLine(e.Data);
else
wasprompt = false;
}
}
};
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
await semaphore.WaitAsync();
while (!p.HasExited)
{
Console.Write($"/SHELL/ {prompt}#> ");
string input = Console.ReadLine();
p.StandardInput.WriteLine(input);
if (input == "exit") break;
await semaphore.WaitAsync();
}
p.WaitForExit();
}
Console.WriteLine("Bye.");
Console.ReadKey();
}
经过几次测试,它看起来像您期望的那样工作。
这个想法是添加$_
到PROMPT
环境变量以强制将提示打印到输出。然后我捕捉到该提示并使用SemaphoreSlim
.
推荐阅读
- dos - DOS在运行时插入段地址
- recursion - Prolog中的尾递归
- java - 从内部连接发布到 Maven 中心
- buffer - AudioKit / AVAudioEngine 依次播放节点
- oracle - USERENV('SESSIONID') 和 USERENV('SID) 之间的区别?
- python - 如何在 R 中保存 logit 模型并在 Python 中导入?
- php - 从 PHP 中的数组中获取特定值
- xamarin.forms - Xamarin 表单集合视图额外填充
- java - 如何在截止日期调用 grpc blockstub 时管理应用程序崩溃
- angular - Angular httpClient - RXJS 用法