2011-05-29 83 views
0

我的代碼讀取在Xcode控制檯總是給人一個錯誤:試圖讀取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); 

    } 

} 

有什麼不對呢?

+0

你想做什麼?你不要讀stderr。 – 2011-05-29 18:54:07

回答

6

您無法讀取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. 考慮到不會有任何方式將應用程序連接到管道或tty,iPhone應用程序可以從控制檯讀取的可能性很小。

  2. 它可以從錯誤文件描述符讀取它甚至是不可能的。