Jac*_*ack 3 c c# input process
这是我的第一个问题,因此我将尽可能详细。我目前正在研究一个C#程序(我们将其称为TestProgram),该程序测试用C编写的另一个程序(我将其称为StringGen)。TestProgram应该在命令窗口中运行StringGen,然后将其输入一组输入字符串并记录每个输出的输出。运行StringGen时,它将启动while循环,等待输入,然后将该输入提交给处理函数,然后返回结果。
我的问题来自于当我尝试让TestProgram向StringGen提交字符串时。我正在将StringGen作为一个进程启动,并尝试使用Process.StandardInput.WriteLine()馈送输入,然后使用Process.StandardOutput.ReadLine()寻找输出。在进一步阐述之前,我将提供一些代码。
这是StringGen的主要功能:
int main() {
char result[255];
char input[255];
do {
fgets(input, 100, stdin);
result = GetDevices(input); //Returns the string required
printf("%s", result);
} while (input != "quit");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我将StringGen定义为进程的C#代码:
Process cmd = new Process();
ProcessStartInfo info = new ProcessStartInfo(command, arguements); // Command is the path to the C executeable for StringGen
info.WorkingDirectory = workingDirectory; // Working Directory is the directory where Command is stored
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.UseShellExecute = false;
cmd.StartInfo = info;
cmd.Start();
Run Code Online (Sandbox Code Playgroud)
然后,我继续使用此过程,如下所示:
using (var cmd)
{
// Loop through the input strings
String response;
foreach (exampleString in StringSet) // Loops through each string
{
cmd.StandardInput.WriteLine(exampleString.text); // This is the problem line
response = cmd.StandardOutput.ReadLine(); // System comes to a halt here
cmd.StandardOutput.Close();
if (response == "Something")
{
// Do this
}
else
{
// Do that
}
}
}
Run Code Online (Sandbox Code Playgroud)
WriteLine命令似乎没有向StringGen提供任何输入,因此系统挂起在ReadLine,因为StringGen没有提供任何输出。我试过在命令行上运行StringGen,它工作正常,并从键盘输入并返回正确的字符串。我已经尝试了所有可以想到的方法,并在该站点以及其他试图找到解决方案的站点中进行了搜索,但是这种代码的每个示例似乎对其他所有人都适用。我看不到我在做什么错。如果有人建议我可以从TestProgram向StringGen程序提交输入的方法,我将不胜感激。如果我遗漏了任何重要内容或不清楚的地方,请告诉我。
注意:我已经在StringGen中尝试了scanf和fgets,它们都产生相同的结果。
我已经尝试过在WriteLine()中使用文字字符串,但是仍然没有输入。
我试过在TestProgram中使用Write()和Flush(),但无济于事。
我试图关闭()输入缓冲区以强制刷新,但这也没有效果。
我对C#不太熟悉,因为我正在编辑其他人的代码以在StringGen上执行测试。
我认为问题出在您的C程序中,而不是您的C#程序中。产生输出时,请不要放在\n最后。因此StandardOutput.ReadLine()将永远等待,因为流中没有行尾标记。
由于C程序的输出用于同步协作程序的步骤,因此在等待下一部分输入之前将其刷新到输出也是一个很好的主意:
printf("%s\n", result);
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)