开发者

How can I invoke linux programs from C#/Mono?

I've been using MonoDevelop and Make to execute some build taks on a C project under linux, but I decided to abandon Make and switch to NAnt since I am more proficient in writing C# programs than Make/shell scripts, so I decided to write a custom NAnt task in C# to replace my Makefile. So, how can I invoke GCC or other shell comma开发者_JS百科nds from C#?

I also need to know how to block the execution until GCC returns.


It's the same as on Windows - use System.Diagnostics.Process. Beware that if you redirect stdout/stderr and the buffers fill up (which is entirely possible using GCC) it can deadlock, so harvest those into StringBuilders.

var psi = new Process.StartInfo ("gcc", "-gcc -arguments") {
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    UseShellExecute = false,
};
var error  = new System.Text.StringBuilder ();
var output = new System.Text.StringBuilder ();

var p = Process.Start (psi);
p.EnableRaisingEvents = true;
p.OutputDataReceived +=
    (object s, DataReceivedEventArgs e) => output.Append (e.Data);
p.ErrorDataReceived  +=
    (object s, DataReceivedEventArgs e) => output.Append (e.Data);

p.WaitForExit ();

FWIW, you might like to consider using custom tasks for MSBuild (i.e. Mono's "xbuild") instead of NAnt, because MonoDevelop's project files are MSBuild files, and MonoDevelop has xbuild integration.


Maybe this will help:

http://mono-project.com/Howto_PipeOutput

It's essentially the same as .NET on Windows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜