Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlWindowsErrorMode = 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_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionAeDebugAuto = 0

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...