Rob*_*cks 4 c# stdin ipc stdout
当我自己的进程的stdin 流上收到数据时,C# 是否提供事件?像Process.OutputDataReceived之类的东西,只有我需要 InputDataReceived 的事件。
我进行了高低搜索,并学会了重定向 stdin->stdout、监视生成的应用程序的输出流和大量其他内容,但没有人显示收到 stdin 时会触发哪个事件。除非我在main().
// dumb polling loop -- is this the only way? does this consume a lot of CPU?
while ((line = Console.ReadLine()) != null && line != "") {
// do work
}
Run Code Online (Sandbox Code Playgroud)
另外,我需要从流中获取二进制数据,如下所示:
using (Stream stdin = Console.OpenStandardInput())
using (Stream stdout = Console.OpenStandardOutput())
{
byte[] buffer = new byte[2048];
int bytes;
while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0) {
stdout.Write(buffer, 0, bytes);
}
}
Run Code Online (Sandbox Code Playgroud)
轮询循环不会消耗太多CPU,因为ReadLine会阻塞并等待。将此代码放入自己的工作线程中,并从中引发事件。据我所知,.NET中没有这样的功能。
编辑:我首先就错了。更正:
您实际上可以从标准输入读取二进制数据,正如这个答案所说:
要读取二进制文件,最好的方法是使用原始输入流 - 这里显示 stdin 和 stdout 之间的“echo”之类的内容:
using (Stream stdin = Console.OpenStandardInput())
using (Stream stdout = Console.OpenStandardOutput())
{
byte[] buffer = new byte[2048];
int bytes;
while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0) {
stdout.Write(buffer, 0, bytes);
}
}
Run Code Online (Sandbox Code Playgroud)