Re: Redirect stderr to NSTextView
Re: Redirect stderr to NSTextView
- Subject: Re: Redirect stderr to NSTextView
- From: "Gerriet M. Denkmann" <email@hidden>
- Date: Tue, 22 Jun 2004 10:53:39 +0200
From: Tom Harrington <email@hidden>
Date: Mon, 21 Jun 2004 14:51:49 -0600
On Jun 20, 2004, at 2:10 PM, Sherm Pendley wrote:
I would log the output to a regular .log file in ~/Library/Logs,
rather than to a temp file - it could be useful to review it later.
But that's a minor point.
To implement the "view log" window, I'd have it start another thread
(to avoid blocking) and in the subthread run "tail -f" with NSTask.
Whenever input is received from the "tail -f", tell the main thread to
append it to the text view. This will save you the trouble of
monitoring the log file, remembering its size when it was last written
to, etc. - all that logic is already present in "tail".
When you close the window, you'll need to terminate the "tail" task
with NSTask's -terminate method, because "tail -f" loops forever and
never exits on its own.
It'd be nicer to actually redirect stderr to a pipe, read data from
there, and append to the text view. It's a lot cleaner than mucking
about with temp files and running "tail" just to collect the data.
A Unix-centered approach would be something like the following.
Adapting this to use NSPipe, NSFilehandle, etc, should be pretty
straightforward. The key would be to get the numeric filehandle for
the pipe, so as to pass it on to dup2() (which I don't think has a
Cocoa equivalent).
int pipefds[2];
char line[80];
if (pipe(pipefds) < 0) {
perror("pipe");
return 0;
}
dup2(pipefds[1], 2);
fprintf(stderr, "foo bar baz\n");
if (read(pipefds[0], line, 80) < 0) {
perror("read");
return 0;
}
printf("Read from pipe: %s\n", line);
--
Tom Harrington
email@hidden
Another way (mentioned in
<
http://www.macosxguru.net/article.php?story=20031219101641977> ) would
be (temporarily) replacing the content of stderr->_write, which has the
advantage that it can easily be switched back to the normal destination
of stderr.
typedef int File_Writer_t(void *, const char *, int);
- (void)someMethodCallingSomeVerboseFunction
{
File_Writer_t *originalFW = stderr->_write ;
stderr->_write = &myOwnWriter ;
someRoutineWhichUsesFprinf( arg1, verbosity );
stderr->_write = originalFW ;
}
static int myOwnWriter( void *inFD, const char *buffer, int size )
{
NSString *tmp = [ [ NSString alloc ] initWithBytes: buffer length:
size encoding: NSUTF8StringEncoding ];
// do what you need with the tmp string here like appending it to a
NSTextView
[ tmp release ] ;
return size ;
}
Gerriet.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.