views:

945

answers:

4

I'm writing a scheduler or sorts. It's basically a table with a list of exes (like "C:\a.exe") and a console app that looks at the records in the table every minute or so and runs the tasks that haven't been run yet.

I run the tasks like this:

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = someExe; // like "a.exe"
p.Start();

How can I tell if a particular task failed? For example what if a.exe throws an unhandled exception? I'd like the above code to know when this happens and update the tasks table with something like "the particular task failed" etc.

How can I do this?

p.s. I'm not using the Sql Agent or the Windows Scheduler because someone else told me not to. He has more "experience" so I'm basically just following orders. Feel free to suggest alternatives.

Thanks!

+4  A: 

I think you're looking for Process.ExitCode, assuming the process returns one. You may need to use WaitForExit() though. There is also an ErrorDataReceived event which is triggered when an app sends to stderr.

Nazadus
See http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx for an example of this.
marcj
+2  A: 

In addition to the ExitCode, you can also do something like this:

string output = p.StandardOutput.ReadToEnd();

That will capture everything that would have been written to a command window. Then you can parse that string for known patterns for displaying errors, depending on the app.

Pete
You need to be careful with deadlock conditions using this! http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
hova
+4  A: 

You can catch the Win32Exception to check if Process.Start() failed due to the file not existing or execute access is denied.

But you can not catch exceptions thrown by the processes that you create using this class. In the first place, the application might not be written in .NET so there might not be a concept of exception at all.

What you can do is check on the ExitCode of the application or read the StandardOutput and StandardError streams to check whether error messages are being posted.

jop
A: 

To expand on what @jop said. You will also need to wait for the process to close. Thus:

        p.Start();
        p.WaitForExit();
        int returnCode = p.ExitCode;

Non-zero codes are typically errors. Some application use negative ones are errors, and positive ones as status codes/warnings.

Jonathan C Dickinson