我需要使用NSPipe通道实现两个线程之间的通信,问题是我不需要通过指定这个方法来调用terminal命令。
[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中实现它?
发布于 2012-12-20 06:52:35
如果我没理解错的话,你可以创建一个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];
}
https://stackoverflow.com/questions/13961799
复制相似问题