Попытка прочитать вывод консоли Xcode - PullRequest
1 голос
/ 29 мая 2011

Мой код для чтения консоли в 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 ]

7 голосов
/ 31 мая 2011

Вы не можете прочитать 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 голос
/ 29 мая 2011
  1. Маловероятно, что приложение для iPhone сможет читать с консоли, учитывая, что не будет никакого способа подключить приложение к каналам или tty.

  2. Даже маловероятно, что он мог прочитать из дескриптора файла ошибки.

...