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
Always good to have different solutions, so here are my two cents:
The idea is to check the stderr filehandle (this is where NSLog
prints to). This solution has reliably been working since at least iOS 4 and keeps doing so in iOS 9, both on the simulator and device.
#import <sys/ioctl.h>
#import <sys/param.h>
#if TARGET_IPHONE_SIMULATOR
#import <sys/conf.h>
#else
// Not sure why <sys/conf.h> is missing on the iPhoneOS.platform.
// It's there on iPhoneSimulator.platform, though. We need it for D_DISK, only:
#if ! defined(D_DISK)
#define D_DISK 2
#endif
#endif
BOOL isDebuggerAttatchedToConsole(void)
{
// We use the type of the stderr file descriptor
// to guess if a debugger is attached.
int fd = STDERR_FILENO;
// is the file handle open?
if (fcntl(fd, F_GETFD, 0) < 0) {
return NO;
}
// get the path of stderr's file handle
char buf[MAXPATHLEN + 1];
if (fcntl(fd, F_GETPATH, buf ) >= 0) {
if (strcmp(buf, "/dev/null") == 0)
return NO;
if (strncmp(buf, "/dev/tty", 8) == 0)
return YES;
}
// On the device, without attached Xcode, the type is D_DISK (otherwise it's D_TTY)
int type;
if (ioctl(fd, FIODTYPE, &type) < 0) {
return NO;
}
return type != D_DISK;
}
The simplest solution actually is
_isDebugging = isatty(STDERR_FILENO);
It isn't exactly the same as telling whether the app is running under debugger, but good enough (even better?) to determine whether the log should be written to disk.