views:

75

answers:

2

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 commands from C#?

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

A: 

Maybe this will help:

http://mono-project.com/Howto_PipeOutput

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

TheNextman
+3  A: 

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.

mhutch
Great code man, I didn't knew MsBuild allowed custom tasks and will certainly look into that.
Thiado de Arruda
MonoDevelop has C project types so it must already have a task for executing gcc right? If so, how can I access that task progamatically on my own custom task? And more importantly, how can I 'insert' my own custom task into a MonoDevelop Project?
Thiado de Arruda