Bir*_*chi 1 xcode cocoa objective-c 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这有什么问题?
您无法读取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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1731 次 |
| 最近记录: |