rendered paste bodyusing System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace ExitCodeTest
{
class Logger
{
Process _p;
StreamWriter _sw;
StreamReader p_out;
StreamReader p_err;
int maxBuffer = 10000;
public Logger(Process p, StreamWriter sw)
{
_p = p;
_sw = sw;
p_out = p.StandardOutput;
p_err = p.StandardError;
Console.Out.WriteLine("Logger created");
}
public void LogOutput(object o)
{
lock (_sw)
{
_sw.WriteLine("LogOutput dropping in");
}
int nRead = 0;
char[] buffer = new char[maxBuffer];
while (!_p.HasExited)
{
nRead = p_out.Read(buffer, 0, 1);
lock (_sw)
{
_sw.Write(buffer, 0, nRead);
}
}
lock (_sw)
{
_sw.WriteLine("Process exited");
}
}
public void LogError(object o)
{
lock (_sw)
{
_sw.WriteLine("LogError also around");
}
int nRead = 0;
char[] buffer = new char[maxBuffer];
while (!_p.HasExited)
{
nRead = p_err.Read(buffer, 0, 1);
lock (_sw)
{
_sw.Write(buffer, 0, nRead);
}
}
lock (_sw)
{
_sw.WriteLine("Process exited");
}
}
}
class Program
{
static void SpawnThreads(Logger l)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(l.LogOutput));
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(l.LogError));
}
static void p_Exited(object o, EventArgs e)
{
Console.Out.WriteLine("p_Exited called");
System.Threading.Thread.Sleep(5000);
Process p = (Process)o;
Console.Out.WriteLine("Exit code in handler: {0}", p.ExitCode);
Console.Out.Flush();
}
static void Main(string[] args)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
System.IO.StreamWriter outfile = new System.IO.StreamWriter("/home/pfernie/tmp/file");
outfile.WriteLine("Main thread, in the house");
outfile.AutoFlush = true;
p.StartInfo.FileName = "mono";
p.StartInfo.Arguments = "/home/pfernie/src/cs/Exiter/Exiter.exe 5";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
Console.Out.WriteLine("Starting: '" + p.StartInfo.FileName + " " + p.StartInfo.Arguments + "'");
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
Logger l = new Logger(p, outfile);
SpawnThreads(l);
Console.Out.WriteLine("Threads spawned");
//if (0 != args.Length)
// p.WaitForExit(1);
Console.Out.WriteLine("May or may not have just WaitForExit()'d");
while (!p.HasExited) ;
System.Threading.Thread.Sleep(5000);
Console.Out.WriteLine("Early exit code: {0}!", p.ExitCode);
System.Threading.Thread.Sleep(5000);
outfile.Close();
Console.Out.WriteLine("Done: {0}!", p.ExitCode);
}
}
}