Find Out if Xcode/LLDB Debugger Is Attached to Current App

This time, I don’t want to find out if the app is compiled as debug/release mode; I want to find out if the debugger is attached.

I found an Objective-C answer on StackOverflow which is based on HockeyApp-iOS.

Here’s my Swift translation, effectively using lazy evaluation of global variables instead of a dispatch_once_t:

let isDebuggerAttached: Bool = {
    var debuggerIsAttached = false

    var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
    var info: kinfo_proc = kinfo_proc()
    var info_size = MemoryLayout<kinfo_proc>.size

    let success = name.withUnsafeMutableBytes { (nameBytePtr: UnsafeMutableRawBufferPointer) -> Bool in
        guard let nameBytesBlindMemory = nameBytePtr.bindMemory(to: Int32.self).baseAddress else { return false }
        return -1 != sysctl(nameBytesBlindMemory, 4, &info, &info_size, nil, 0)

    if !success {
        debuggerIsAttached = false

    if !debuggerIsAttached && (info.kp_proc.p_flag & P_TRACED) != 0 {
        debuggerIsAttached = true

    return debuggerIsAttached

I posted my version to StackOverflow, too, of course. Find it here.