Detect If Your Application Is Running In The Debugger
February 11, 2013
The C function below returns true or false depending on whether or not the application making the call is running in the Xcode debugger. Honestly, I’ve not come up with a scenario when I’ll need this, however, anything that makes system level calls is an interesting study in how things in iOS.
Notice the code below is a C function, not an Objective-C method:
static bool debuggerRunning(void) { int junk; int mib[4]; struct kinfo_proc info; size_t size; info.kp_proc.p_flag = 0; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); size = sizeof(info); junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); assert(junk == 0); // If P_TRACED flag set, debugger running return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); } |
You can call the above code as follows:
if (debuggerRunning()) NSLog(@"Debugger running"); else NSLog(@"Debugger not running"); |
This code example is courtesy Apple from their Technical Q&A section.



