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.

2 Answers 2

3

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.

2
  • Great code man, I didn't knew MsBuild allowed custom tasks and will certainly look into that. Jun 11, 2010 at 19:31
  • 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? Jun 11, 2010 at 19:56
0

Maybe this will help:

http://mono-project.com/Howto_PipeOutput

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.