2012-12-19 40 views
6

我需要使用NSPipe通道實現兩個線程之間的通信,問題是我不需要通過指定此方法來調用終端命令。使用NSPipe進程之間的通信,NSTask

[task setCurrentDirectoryPath:@"....."]; 
[task setArguments:]; 

我只需要編寫一些數據

NSString * message = @"Hello World"; 
[stdinHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; 

和其他線程收到此消息

 NSData *stdOutData = [reader availableData]; 
NSString * message = [NSString stringWithUTF8String:[stdOutData bytes]]; //My Hello World 

例如在C#這樣的事情可以用NamedPipeClientStream可以輕鬆完成, NamedPipeServerStream類,其中管道通過id字符串進行註冊。

如何在Objective-C中實現它?

+0

是你的問題在同一個進程中約2牙,或約通過管道進行通信的單獨的進程? –

+0

它關於通過管道進行通信的兩個線程 – Andrew

+0

如何實現通過管道進行通信的獨立進程? – vadivelu

回答

3

如果我正確理解你的問題,你可以創建一個NSPipe,並使用一端閱讀和一端寫作。例如:

// Thread function is called with reading end as argument: 
- (void) threadFunc:(NSFileHandle *)reader 
{ 
    NSData *data = [reader availableData]; 
    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", message); 
} 

- (void) test 
{ 
    // Create pipe: 
    NSPipe *pipe = [[NSPipe alloc] init]; 
    NSFileHandle *reader = [pipe fileHandleForReading]; 
    NSFileHandle *writer = [pipe fileHandleForWriting]; 

    // Create and start thread: 
    NSThread *myThread = [[NSThread alloc] initWithTarget:self 
               selector:@selector(threadFunc:) 
                object:reader]; 
    [myThread start]; 

    // Write to the writing end of pipe: 
    NSString * message = @"Hello World"; 
    [writer writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; 

    // This is just for this test program, to avoid that the program exits 
    // before the other thread has finished. 
    [NSThread sleepForTimeInterval:2.0]; 
} 
+0

謝謝!效果很好 – Andrew

+0

@Andrew:不客氣,我很高興它有幫助。 –

+1

好的。我很困惑。這是如何工作的,以允許兩個應用程序相互交談。管道在哪裏設置了某種標識符以在應用程序之間共享?還有多少應用程序可以使用一個管道集? –