【发布时间】:2012-04-01 14:58:00
【问题描述】:
所以,这是我的代码:
- (void)runCmd:(NSString *)cmd withArgs:(NSArray *)args
{
NSLog(@"\nRunning ::\n\tCmd : %@\n\tArgs : %@",cmd, args);
[theSpinner start];
if (task)
{
[task interrupt];
}
else
{
task = [[NSTask alloc] init];
[task setLaunchPath:cmd];
[task setArguments:args];
[pipe release];
pipe = [[NSPipe alloc] init];
[task setStandardOutput:pipe];
NSFileHandle* fh = [pipe fileHandleForReading];
NSNotificationCenter* nc;
nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self];
[nc addObserver:self
selector:@selector(dataReady:)
name:NSFileHandleReadCompletionNotification
object:fh];
[nc addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:fh];
[nc addObserver:self
selector:@selector(taskTerminated:)
name:NSTaskDidTerminateNotification
object:task];
[task launch];
[fh readInBackgroundAndNotify];
}
}
- (void)dataAvailable:(NSNotification*)n
{
NSLog(@"Data Available : %@",n);
}
- (void)dataReady:(NSNotification*)n
{
NSData* d;
d = [[n userInfo] valueForKey:NSFileHandleNotificationDataItem];
NSLog(@"Data Ready : %@",n);
if ([d length])
{
NSLog(@"Data Ready : %@",[[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]);
}
}
- (void) taskTerminated:(NSNotification*)note
{
NSLog(@"Task Terminated : %@",note);
[task release];
task = nil;
[theSpinner stop];
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:[NSString stringWithFormat:@"Command finished"]];
[alert runModal];
}
我尝试过运行带有参数的命令(例如 /usr/bin/php 的 php 解释器)(例如要由 php test.php 解释的文件)。
事情是这样的:
- 脚本运行良好
- 但是,我收到了
Data Ready和Task Terminated在我设法获得所有输出之前通知。 (我是说,dataReady:函数仅获取
输出,其余部分无处可寻...)
我基本上想在命令运行时异步读取所有输出。
有什么想法吗?我做错了什么?
谢谢!
【问题讨论】:
标签: objective-c cocoa asynchronous nstask nsfilehandle