xecução assíncrona do comando shell não está funcionando corretamen
Então, este é o meu código:
- (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];
}
Tentei executar um comando (por exemplo, o interpretador php em/usr/bin/php
) com argumentos (por exemplo, o arquivo a ser interpretado por phptest.php
).
A coisa é
O script roda bem MAS, estou recebendo umData Ready
eTask Terminated
notificação ANTES de conseguir obter toda a saída. (Quero dizer, odataReady:
função @ busca apenas a primeira parte dooutput e o resto não é encontrado em nenhum lugar ...)
Eu basicamente quero ler, de forma assíncrona, todas as saídas - enquanto o comando está sendo executad
Alguma ideia? O que estou fazendo de errado
Obrigado