emmmmm,最近在研究WFDB工具箱,C语言写的,无奈本人C语言功底不够,只想直接拿来用,于是打算通过ProcessStartInfo来调取编译出来的exe程序获取输出。

一开始就打算偷懒,从园子里的前辈blog上偷来部分代码,和着自己写的代码差不多就写了以下调取程序的代码:

         /// <summary>
/// 调用Exe核心代码
/// </summary>
/// <param name="exeFileName"></param>
/// <param name="args"></param>
public void RunExe(string exeFileName, string args = "")
{
try
{ Process p = new Process(); p.StartInfo = new ProcessStartInfo(exeFileName, args); p.StartInfo.Arguments = args;
//p.StartInfo.WorkingDirectory = @"C:\MinGW\msys\1.0\home\61125\wfdb-10.6.1\build\bin";
p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false;
//绑定事件
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += P_ErrorDataReceived; p.Start();
p.BeginOutputReadLine();//开始读取输出数据
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

然后使用时发现了问题,按照wfdb 中app的设计,直接调取exe是会弹出help内容的,可是我自己调用却不行。

无奈自己就搭建C环境,MinGw配合Visual Code配置了一把,踩了好多坑,才在windows环境下跑起了wfdb并能够调试。具体坑就不谈了。(有意愿的小伙伴可以和我沟通交流一下~)

研究了C代码发现异常输出都是通过

 fprintf(stderr, "xxxxx")

此类形式输出的,搜索一下,查看了前辈的文章(https://www.cnblogs.com/tshua/p/5730658.html)发现输出流是有讲究的,不是全部通过Output通道发送的。

于是困扰了我两天的问题解决方案如下:

         /// <summary>
/// 调用Exe核心代码
/// </summary>
/// <param name="exeFileName"></param>
/// <param name="args"></param>
public void RunExe(string exeFileName, string args = "")
{
try
{ Process p = new Process(); p.StartInfo = new ProcessStartInfo(exeFileName, args); p.StartInfo.Arguments = args;
//p.StartInfo.WorkingDirectory = @"C:\MinGW\msys\1.0\home\61125\wfdb-10.6.1\build\bin";
p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false;
//绑定事件
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += P_ErrorDataReceived; p.Start();
p.BeginOutputReadLine();//开始读取输出数据
p.BeginErrorReadLine();//开始读取错误数据,重要!
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

加入一行关键的

p.BeginErrorReadLine();//开始读取错误数据,重要!

就解决了问题。

emmmm。。(lll¬ω¬)

仅以此篇随笔防止其他小伙伴和我一样走弯路≡(▔﹏▔)≡

05-11 13:56