5 * Interface of class HBOutputRedirect.
8 #import <Cocoa/Cocoa.h>
11 * This class is used to redirect @c stdout and @c stderr outputs. It is never
12 * created directly; @c stdoutRedirect and @c stderrRedirect class methods
13 * should be use instead.
15 * @note Redirection is done by replacing @c _write functions for @c stdout and
16 * @c stderr streams. Because of this messages written by NSLog(), for
17 * example are not redirected. I consider this a good thing, but if more
18 * universal redirecting is needed, it can be done at file descriptor
21 @interface HBOutputRedirect : NSObject
23 /// Set that contains all registered listeners for this output.
24 NSMutableSet *listeners;
26 /// Selector that is called on listeners to forward the output.
27 SEL forwardingSelector;
29 /// Output stream (@c stdout or @c stderr) redirected by this object.
32 /// Pointer to old write function for the stream.
33 int (*oldWriteFunc)(void *, const char *, int);
41 - (void)addListener:(id)aListener;
42 - (void)removeListener:(id)aListener;
46 /* Here is another technique to redirect stderr, but it is done at lower level
47 which also redirects NSLog() and other writes that are done directly to the
48 file descriptor. This method is not used by HBOutputRedirect, but should
49 be easy to implement if needed. Code is untested, but this is shows basic
50 idea for future reference.
53 NSPipe *pipe = [[NSPipe alloc] init];
55 // Connect stderr to the writing end of the pipe
56 dup2([[pipe fileHandleForWriting] fileDescriptor], STDERR_FILENO);
58 // Get reading end of the pipe, we can use this to read stderr
59 NSFileHandle *fh = [pipe fileHandleForReading];