How do I debug an exe running through Windows Scheduler?

只愿长相守 提交于 2019-12-06 10:10:07
Just a Bill

See this Stack Overflow question How Can I Use DebugBreak in C#

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).

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.

You can set a key under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options that will attach debugger to the process when the process is launched. You can read how to do this in this KB Article.

There are couple of gotchas with this approach:

To debug using VS, you need to actually specifyg VSJitDebugger.exe in the IFEO options for your executable. You will also have to specify the debugging engine to use manually. More details here.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!