How do I debug an exe running through Windows Scheduler?

Paul Rowland picture Paul Rowland · Feb 26, 2009 · Viewed 7.3k times · Source

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

Answer

LeopardSkinPillBoxHat picture LeopardSkinPillBoxHat · Feb 26, 2009

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