2017-03-13 95 views
0

我正在使用NSTask來運行交互式的cli應用程序。我用它來通過USB連接拉取數據。使用NSTask交互式訪問命令

我打開一個帶有輪廓和錯誤管道的NSTask,但是當我發出一個命令時,它可以工作,但是在循環中旋轉沙灘球從輸出中提取數據。

我希望能夠混搭 - (IBAction爲)點擊:(ID)發送按鈕執行help命令,並得到輸出回:

NSTask *usbCommandTask; 
NSPipe *outPipe; 
NSPipe *inPipe; 
NSPipe *errorPipe; 
NSFileHandle *inFile; 
NSFileHandle *outFile; 
NSTimer *pollTimer; 
dispatch_queue_t mtpTask; 

@implementation AppDelegate 


- (void)commandNotification:(NSNotification *)notification 
{ 
    NSData *data = nil; 

    while ((data = [outFile availableData]) && [data length]){ 
     NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"Data: %@",myString); 
     } 
    NSLog(@"Execution never gets here"); 

} 

-(void)checkTask 
{ 
    if(usbCommandTask){ 
     if([usbCommandTask isRunning])NSLog(@"Task running"); else NSLog(@"Task dead"); 

    } else NSLog(@"Task is nil"); 


} 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 



    usbCommandTask = [[NSTask alloc] init]; 
    [usbCommandTask setLaunchPath:@"/Applications/usb-debugger-cli"]; 
    [usbCommandTask setCurrentDirectoryPath:@"/"]; 
    [usbCommandTask setArguments:[NSArray arrayWithObject:@"-i"]]; 
    inPipe = [NSPipe pipe]; 
    [usbCommandTask setStandardInput:inPipe]; 




    outPipe = [NSPipe pipe]; 
    [usbCommandTask setStandardOutput:outPipe]; 
    errorPipe = [NSPipe pipe]; 
    [usbCommandTask setStandardError:errorPipe]; 

    outFile = [outPipe fileHandleForReading]; 
    inFile = [inPipe fileHandleForWriting]; 

    [outFile waitForDataInBackgroundAndNotify]; 



    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(commandNotification:) 
               name:NSFileHandleDataAvailableNotification 
               object:nil]; 



    pollTimer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(checkTask) userInfo:nil repeats:TRUE]; 
    [usbCommandTask launch]; 
    NSLog(@"Launched"); 



} 


- (void)applicationWillTerminate:(NSNotification *)aNotification { 
    // Insert code here to tear down your application 
    if(usbCommandTask)[usbCommandTask terminate]; 


} 


- (IBAction)clicked:(id)sender { 

    if(usbCommandTask){ 
    NSString *[email protected]"help\n"; 
    NSData *commandData=[NSData dataWithBytes:command.UTF8String length:command.length]; 

    [inFile writeData:commandData]; 
    } 
    else 
    {NSLog(@"Comamnd task dead"); 
    } 
} 

回答

0
[outFile availableData] 

實際上是一個阻塞調用有是沒有數據或明確的EOF,所以這將永遠阻止,而我使用:

data = [outFile availableData]; 
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
NSLog(@"Data: %@",myString); 
[outFile waitForDataInBackgroundAndNotify];