Reputation: 16327
My code to read the console in Xcode always gives an error :
read: Bad file descriptor
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Some text...");
int fd;
char ch[1024];
fd = read(stderr,ch, sizeof(ch));
if(fd == -1) {
perror("read");
} else {
NSLog(@"Data Read : %s", ch);
}
}
What is wrong with this?
Upvotes: 2
Views: 1828
Reputation: 17898
You can't read stderr, but you can redirect it. Like this:
- (void) redirectStandardError
{
stderrPipe = [NSPipe pipe];
stderrPipeReadHandle = [stderrPipe fileHandleForReading];
dup2( [[stderrPipe fileHandleForWriting] fileDescriptor], fileno(stderr));
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:NSFileHandleReadCompletionNotification
object:stderrPipeReadHandle];
[stderrPipeReadHandle readInBackgroundAndNotify];
}
- (void) handleNotification:(NSNotification*)notification {
[stderrPipeReadHandle readInBackgroundAndNotify];
NSString* str = [[NSString alloc] initWithData:[[notification userInfo] objectForKey:NSFileHandleNotificationDataItem] encoding:NSASCIIStringEncoding];
// Do something with str...
[str release];
}
Upvotes: 8
Reputation: 8513
It's highly unlikely that an iPhone app can read from the console, considering there will not be any way to connect an app to pipes or tty's.
It's even unlikelier that it could read from the error file descriptor.
Upvotes: 1