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?
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With