Detecting the Debugger

Q: How do I determine if I'm being run under the debugger?

A: How do I determine if I'm being run under the debugger?
The code in Listing 1 shows the best way to do this.

#include <assert.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>

static bool AmIBeingDebugged(void)
    // Returns true if the current process is being debugged (either 
    // running under the debugger or has a debugger attached post facto).
{
    int                 junk;
    int                 mib[4];
    struct kinfo_proc   info;
    size_t              size;

    // Initialize the flags so that, if sysctl fails for some bizarre 
    // reason, we get a predictable result.

    info.kp_proc.p_flag = 0;

    // Initialize mib, which tells sysctl the info we want, in this case
    // we're looking for information about a specific process ID.

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PID;
    mib[3] = getpid();

    // Call sysctl.

    size = sizeof(info);
    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
    assert(junk == 0);

    // We're being debugged if the P_TRACED flag is set.

    return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}
Important: Because the definition of the kinfo_proc structure (in <sys/sysctl.h>) is conditionalized by __APPLE_API_UNSTABLE, you should restrict use of the above code to the debug build of your program.
https://developer.apple.com/library/mac/qa/qa1361/_index.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,081评论 0 23
  • 那只手,我所怀念的最温暖的鼓励…… “天啊,今天也太倒霉了。”我一个人坐在书桌前小声嘟囔着。今天真是事事不顺心,看...
    朝秦暮恋阅读 439评论 2 3
  • 一路上一个三十出头的妇女用尽了力气在咆哮,车里,密闭空间,毫无疑问这声音立体环绕,大家忍着耳朵的刺痛一言不发,因为...
    麻蹦蹦阅读 169评论 0 0
  • 午后,漫步在花圃里,满眼是开得正艳的红杜鹃,不知道为什么,对于杜鹃我并不十分钟爱,不知道是因为它的花朵并不美丽呢还...
    黯黯红尘一路相伴阅读 338评论 3 7