[Mono-list] executing a tool from within c#
Colin JN Breame
colin at breame.net
Thu Mar 9 05:20:20 EST 2006
On Thursday 09 March 2006 10:04, Malte Dreschert wrote:
> Sorry,
> I forgot to put a headline on top.
>
> So again: How can I execute a program from within a mono/c# application.
>
> Thanks you and so long.
Malte,
I use something along the lines of what is below.
However, I pretty sure that execute_capture_output can cause deadlocks within
the running application. This is due to the ordering of the lines:
string output = p.StandardError.ReadToEnd();
output += p.StandardOutput.ReadToEnd();
The application can deadlock because it is blocked writting to its' stdout
which is not read from until its' stderr is closed (which will never happen
because it is blocked).
Although this is a known issue I'm not sure there is a way around it and
no-one has suggested a solution. Anyhow, this works for the most part.
Colin
---
using System.Diagnostics;
string output = p.StandardError.ReadToEnd();
output += p.StandardOutput.ReadToEnd();
namespace colib {
public class process_t {
public static string execute_capture_output(string cmd_line,
out int exit_code) {
using (Process p = new Process()) {
int i = cmd_line.IndexOf(' ');
if (i == -1) {
p.StartInfo.FileName = cmd_line;
} else {
p.StartInfo.FileName = l_t.left(cmd_line, i);
p.StartInfo.Arguments = l_t.right(cmd_line, -i-1);
}
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
string output = p.StandardError.ReadToEnd();
output += p.StandardOutput.ReadToEnd();
p.WaitForExit();
exit_code = p.ExitCode;
return output;
}
}
public static int execute(string path) {
Process p = new Process();
int i = path.IndexOf(' ');
if (i == -1) {
log_t.info(path);
p.StartInfo.FileName = path;
} else {
p.StartInfo.FileName = l_t.left(path, i);
p.StartInfo.Arguments = l_t.right(path, -i-1);
}
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
int exit_code = p.ExitCode;
p.Close();
return exit_code;
}
}
}
More information about the Mono-list
mailing list