3

I'm using Windows Scheduler to run an exe I have written.

How can I jump into a debug session when the scheduler starts my exe?

Update 1. I had thought of doing a Thread.Sleep and then Attach to Process. When I tried it, it says Debugger is already attached to process...

4

4 回答 4

5

You could just call DebugBreak() from within your program.

According to the MSDN page, DebugBreak does the following:

Causes a breakpoint exception to occur in the current process. This allows the calling thread to signal the debugger to handle the exception.

To cause a breakpoint exception in another process, use the DebugBreakProcess function.

You can then attach your debugger at this point, and continue running the program.

The only problem with this solution is that you need to make the DebugBreak() in the code conditional, so that it won't break every time the program is run. Maybe you achieve this through an environment variable, registry setting, or a parameter which the scheduler passes in to the program to ensure that it breaks when it starts up.

Example code

Here's some untested example code reading an environment variable:

int main()
{
    char *debugBreakChar = getenv("DEBUG_BREAK");
    int debugBreak = atoi(debugBreakChar);
    if (debugBreak)
    {
        DebugBreak();
    }

    // Rest of the program follows here
}

Now all you need to do is set the environment variable as a system variable, and ensure that it's accessible from the same shell context as the scheduler (rebooting will achieve this):

set DEBUG_BREAK=1

Now the program will break on startup, allowing you to attach a debugger. Changing the environment variable to 0, or un-setting it, will allow the program to run normally.

Environment variables are a bit fiddly in this regard, as they are context-based and you need to know that the scheduler runs from the same environmental context. Registry values are better than this, and you can read a registry value using RegQueryValueEx in your code instead (you'll need to include windows.h to use this function).

于 2009-02-26T03:17:42.137 回答
2

Attach to Process will work (from within Visual Studio), although you may need to add a sleep statement at the beginning of your code if it is a fast process so that you can attach before it starts your main logic.

于 2009-02-26T03:17:28.440 回答
1

您可以在其下设置一个键,该键HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options将在启动进程时将调试器附加到进程。您可以在此知识库文章中阅读如何执行此操作。

这种方法有几个问题:

要使用 VS 进行调试,您需要在可执行文件的 IFEO 选项中实际指定VSJitDebugger.exe。您还必须指定要手动使用的调试引擎。更多细节在这里

于 2009-02-26T03:55:54.433 回答
-2

"Attach to Process" in Visual Studio's Debug menu.

于 2009-02-26T03:14:20.447 回答