所以,这是我的代码:
- (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:
函数只获取输出的第一部分,
其余部分无处可寻……)
我基本上想异步读取所有输出 - 当命令运行时。
有任何想法吗?我究竟做错了什么?
谢谢!