如何重定向STDOUT到NSTextView? [英] How to redirect STDOUT to a NSTextView?
本文介绍了如何重定向STDOUT到NSTextView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能告诉我如何将Stdout重定向到NSTextView?
Could anybody show me how to redirect the Stdout to a NSTextView?
以及NSLog打印的信息是否属于std?
and whether the info print by NSLog belong to the std?
感谢
推荐答案
下面的代码使用 dup2
将stdout插入到 NSPipe
对象的写端。使用GCD分派源来观察读端,它从管道读取数据并将其附加到textview。
The code below uses dup2
to plug stdout onto the write-end of an NSPipe
object. The read-end is observed with a GCD dispatch source, that reads data from the pipe and appends it to a textview.
NSPipe* pipe = [NSPipe pipe];
NSFileHandle* pipeReadHandle = [pipe fileHandleForReading];
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, [pipeReadHandle fileDescriptor], 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_event_handler(source, ^{
void* data = malloc(4096);
ssize_t readResult = 0;
do
{
errno = 0;
readResult = read([pipeReadHandle fileDescriptor], data, 4096);
} while (readResult == -1 && errno == EINTR);
if (readResult > 0)
{
//AppKit UI should only be updated from the main thread
dispatch_async(dispatch_get_main_queue(),^{
NSString* stdOutString = [[NSString alloc] initWithBytesNoCopy:data length:readResult encoding:NSUTF8StringEncoding freeWhenDone:YES];
NSAttributedString* stdOutAttributedString = [[NSAttributedString alloc] initWithString:stdOutString];
[self.logView.textStorage appendAttributedString:stdOutAttributedString];
});
}
else{free(data);}
});
dispatch_resume(source);
NSLog(@...)
不输出到 stdout
though - 它输出到 stderr
。如果要将其重定向到您的textview,请更改
NSLog(@"...")
does not output to stdout
though - It prints to stderr
. If you want to redirect that into your textview, change
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));
到
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stderr));
这篇关于如何重定向STDOUT到NSTextView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文