It doesn’t seem like this should be so hard, but it is. The Win32 CreateProcess API call has two nifty ways to do this.
1) Inherit handles from the parent process. So open the log file as your own stdout and stderr, then launch the child process.
2) Specify the stdout and stderr handles explicitly to the CreateProcess call.
Now, we all know that in .NET using win32 api calls is naughty, so let’s try using System.Diagnosis.Process.Start() instead. It has a very convient methods for capturing the output, but no way to set the handles to a file. Rats.
So all we have left is a hack. Launch cmd.exe and have it redirect the output as described here: http://weblogs.asp.net/israelio/archive/2004/08/31/223447.aspx
icky Oh and wait, the process exits immediatly, and the Process.ExitCode is always 1. Arg!
Ok, so we need another hack. How about instead of starting cmd.exe we just run a bat file.
bat.WriteLine(“@echo off”);
bat.WriteLine(“foo.exe -arg >” + dumpDir + “\\foo_arg.txt”);
bat.Close();
Process task = new Process();
task.StartInfo.UseShellExecute = false;
task.StartInfo.FileName = “foo.bat”;
task.StartInfo.Arguments = “”;
task.Start();
task.WaitForExit();
Truly horrific, but it has the advantage of working! Of course this is subject to a race condition where foo.bat could be replaced with another file by a malicious process, and it’s evil commands would be executed within our user context. I don’t know how to fix that. Perhaps generate a random path name, create a directory, change the ACL’s to prevent anyone from creating files in there, create the batch file in the directory, and then run it. Maybe.