[英]Why can't I get the output of a C++ program using Process in C#?
我有一個C ++程序,它使用wprintf_s
函數將結果打印到命令行。 但是當我在C#中使用Process
來讀取程序的輸出時,我無法得到它的任何說法。 但是當我在wprintf_s
語句之后添加了一個fflush(stdout)
,我終於可以在我的C#程序中讀取標准輸出了。
我用來啟動進度的代碼是:
var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "FILENAME",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
StringCollection values = new StringCollection();
proc.OutputDataReceived += (s, args) => {
lock (values) {
values.Add(args.Data);
}
};
proc.BeginOutputReadLine();
proc.WaitForExit();
誰能告訴我為什么fflush(stdout)
會起作用?
輸出在C ++進程中緩沖,並且將保持不變,直到緩沖區已滿或刷新為止,例如通過調用fflush()
,關閉流或其他依賴於操作系統的原因。
fflush()
只是將輸出緩沖區中的任何數據寫入流中。
如果您不想顯式調用fflush()
,可以考慮通過使用第二個參數的NULL指針調用setbuf()
來在輸出流上設置unbuffered模式:
#include <stdio.h>
#include <unistd.h>
int main()
{
setbuf(stdout, (char *)NULL);
while (1)
{
fputs("hi there\n", stdout);
sleep(1);
}
}
現在輸出將立即出現。
請注意,如果stdout
是終端,則不需要setbuf(f, NULL)
,因為這是終端設備的默認行為。 如果stdout
是一個管道,那么setbuf(f, NULL)
將使它無緩沖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.