Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a crash in a process launched via System.Diagnostics.Process?

I'm launching an external process with System.Diagnostics.Process. This is part of a batch job, so if one process crashes, I'd like to handle it and let the rest continue.

What currently happens is Windows pops up a dialog telling me that the program has crashed, and only once I've dismissed that manually does the process exit.

According to this question, the Process.Responding property is only available for programs with UIs (the process I'm launching is a console app).

I also looked at the various events a process provides, but none of them are fired on crashing.

Any ideas?

like image 505
meatvest Avatar asked Mar 23 '09 11:03

meatvest


1 Answers

Try setting the registry following registry value to value DWORD 2:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ErrorMode = 2

This will affect every process on the machine.

Reference: How to Get Rid of System and Application Popup Messages

If you have the source code to the program that crashes, you can prevent the popups by catching all structured exceptions and exiting without popping up a message box. How you do this depends on the programming language used.

If you don't have the source, use the SetErrorMode function in the parent to suppress popups. The error mode is inherited by subprocesses. You must set UseShellExecute to false for this to work:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace SubProcessPopupError
{

    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int SetErrorMode(int wMode);

        static void Main(string[] args)
        {
            int oldMode = SetErrorMode(3);
            Process p;
            ProcessStartInfo ps = new ProcessStartInfo("crash.exe");
            ps.UseShellExecute = false;
            p = Process.Start(ps);
            SetErrorMode(oldMode);
            p.WaitForExit();
        }
    }
}

If you are getting a dialog saying "Do you want to debug using the selected debugger?", you can turn that off by setting this registry value to 0.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto = 0

However, I don't think this will come up if you have set the error mode to 3 as explained above.

like image 56
Carlos A. Ibarra Avatar answered Nov 15 '22 07:11

Carlos A. Ibarra