What is the best way to redirect stdout to NSTextView in Cocoa?

cocoa, stdout, subprocess

Solution

I was looking to do the same thing and came across this post. I was able to figure it out after reading this and Apple's documentation. I'm including my solution here. "pipe" and "pipeReadHandle" are declared in the interface. In the init method I included the following code:

pipe = [NSPipe pipe] ;
pipeReadHandle = [pipe fileHandleForReading] ;
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout)) ;

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNotification:) name: NSFileHandleReadCompletionNotification object: pipeReadHandle] ;
[pipeReadHandle readInBackgroundAndNotify] ;

The handleNotification: method is

[pipeReadHandle readInBackgroundAndNotify] ;
NSString *str = [[NSString alloc] initWithData: [[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] encoding: NSASCIIStringEncoding] ;
// Do whatever you want with str 

Problem

Hi: I want to redirect stdout to a NSTextView. Could this also work with outputs of subprocesses? What might be the best way to achieve this? EDIT: According to Peter Hosey answer I implemented the following. But I do not get a notification. What am I doing wrong? ``` NSPipe *pipe = [NSPipe pipe]; NSFileHandle *pipeHandle = [pipe fileHandleForWriting]; dup2(STDOUT_FILENO, [pipeHandle fileDescriptor]); NSFileHandle *fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:pipeHandle]; [fileHandle acceptConnectionInBackgroundAndNotify]; NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter]; [dnc addObserver:self selector:@selector(handleNotification:) name:NSFileHandleConnectionAcceptedNotification object:fileHandle]; ```

Original source