objective-c - 进程间通信使用NSPipe,NSTask

标签 objective-c ipc nstask nspipe

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

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

最佳答案

如果我正确理解你的问题,你可以创建一个 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];
}

关于objective-c - 进程间通信使用NSPipe,NSTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961799/

相关文章:

ios - 获取用户在 Objective-C 中订阅的所有主题

iphone - Cocos2d 检测特定 Sprite 上的触摸

ios - 在 iOS 9.0 中使用服务

javascript - Electron.js ipc.sendSync 卡住

perl - Perl中的system,exec和backticks之间有什么区别?

bash - 如何向/bin/bash传递参数?

cocoa - 如何使用确定的 NSProgressIndicator 来检查 NSTask 的进度? - cocoa

cocoa - 使用通知从 NSTask 实时获取数据不起作用

objective-c - 在 iOS5 中使用 Twitter 框架提示登录警报?

c++ - 为什么 msgrcv() 将垃圾字符输入缓冲区?