检测 iOS 应用程序是否在调试器中运行 [英] Detecting if iOS app is run in debugger
问题描述
我将我的应用程序设置为将调试输出发送到控制台或日志文件.现在,我想在代码中决定是否
I set up my application to either send debugging output to console or a log file. Now, I'd like to decide with in the code whether
- 它在调试器(或模拟器)中运行,因此有一个控制台窗口,我想直接读取输出,或者如果
- 没有控制台窗口,因此应该将输出重定向到一个文件.
有没有办法确定应用程序是否在调试器中运行?
Is there a way to determine if the app runs in the debugger?
推荐答案
技术问答 1361 (进入 Mac 库 和 iOS 库中的条目;它们是相同的).
There's a function from Apple to detect whether a program is being debugged in the Technical Q&A 1361 (entry in Mac library and entry in iOS library; they are identical).
来自技术问答的代码:
#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 );
}
还要注意问答末尾的这个注释:
Also pay attention to this note at the end of the Q&A:
重要提示:因为kinfo_proc
结构的定义(在
中)是由条件化的__APPLE_API_UNSTABLE
,您应该将上述代码的使用限制在您程序的调试版本中.
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.
这篇关于检测 iOS 应用程序是否在调试器中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!