2014-10-02 3 views
1

이 코드는 지금까지 가지고 있었고 목표는 NSTask의 특정 출력에 작용하는 것입니다. 본질적으로 (My NSTask)는 시간이 지남에 따라 콘솔에 문자열을 출력하는 프로그램입니다. 특정 문자열이 콘솔에 표시되면 내 코코아 Objective-C 앱에서 메소드를 호출 할 수 있기를 바랍니다. 내 생각은 전달 된 문자열이 동작을 보증하는지 확인하는 내 앱에 콘솔 출력을 파이프하는 것입니다.NSTask Pipe에서 데이터를 읽을 수있게됩니다.

NSPipe *pipe = [NSPipe pipe]; 
    NSFileHandle *file = pipe.fileHandleForReading; 

    self.task = [[NSTask alloc] init]; 

    [self.task setStandardOutput: pipe]; 
    [self.task setStandardError: [self.task standardOutput]]; 

    self.task.launchPath = @"/usr/local/bin/taskThing"; 
    self.task.arguments = @[@"taskArg"]; 

    [self.task launch]; 


    NSMutableData *data = [NSMutableData dataWithCapacity:512]; 
    while ([self.task isRunning]) { 
     [data appendData:[file availableData]]; 
    } 
    [file closeFile]; 

    NSString *taskOut = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"task returned: %@ END", taskOut); 

기본적으로 NSTasks 프로세스를 종료 할 때까지 while 루프가 응용 프로그램을 계속 읽음으로 인해 응용 프로그램이 "충돌"합니다. 프로세스를 종료하면 작업의 모든 기록 된 출력이 기록됩니다. 그래서 일종의 작품들, 내가 할 수 있기를 원하는 것은 Tasks 출력물이 나타날 때 행동하는 것입니다. 작업이 계속 실행되어 파이프 된 데이터를 받기 전에 멈출 수 있기를 기다립니다. 어떤 아이디어?

추신. 방금 waitForDataInBackgroundAndNotify에 대한 언급을 보았습니다. 도움이되기를 바랍니다.

답변

0

나는 더 많은 것을 waitForDataInBackgroundAndNotify로 들여다 보았다. 위의 코드에서 작업을 실행 한 후 나는 이후의 모든 라인을 삭제하고 알림 관찰자 새로운 방법에서

NSPipe *pipe = [NSPipe pipe]; 
NSFileHandle *file = pipe.fileHandleForReading; 

self.task = [[NSTask alloc] init]; 

[self.task setStandardOutput: pipe]; 
[self.task setStandardError: [self.task standardOutput]]; 

self.task.launchPath = @"/usr/local/bin/taskThing"; 
self.task.arguments = @[@"taskArg"]; 

[self.task launch]; 


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outData:) 
name:NSFileHandleDataAvailableNotification object:initialOutputFile]; 

[file waitForDataInBackgroundAndNotify]; 

으로 대체; "outData :"

- (void)outData:(NSNotification *)notification { 
NSFileHandle *outputFile = (NSFileHandle *) [notification object]; 
NSData *data = [outputFile availableData]; 

if([data length]) { 
    NSString *temp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"Here: %@", temp); 
} 

[outputFile waitForDataInBackgroundAndNotify]; 

}

이 모두이 question

기반으로했다