试图阅读Xcode的控制台输出

时间:2011-05-29 18:49:31

标签: objective-c xcode cocoa stderr

我在Xcode中读取控制台的代码总是出错:

  

读:错误的文件描述符

#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);

    }

}

这有什么问题?

2 个答案:

答案 0 :(得分:7)

您无法读取stderr,但可以重定向它。像这样:

- (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];
}

答案 1 :(得分:1)

  1. 考虑到没有任何方法可以将应用程序连接到管道或tty上,iPhone应用程序极不可能从控制台读取。

  2. 它甚至可以从错误文件描述符中读取它。