6

我需要使用 NSPipe 通道实现两个线程之间的通信,问题是我不需要通过指定此方法来调用终端命令。

[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 中实现它?

4

1 回答 1

4

如果我正确理解您的问题,您可以创建一个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];
}
于 2012-12-19T22:52:35.317 回答