首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用NSPipe、NSTask实现进程间的通信

使用NSPipe、NSTask实现进程间的通信
EN

Stack Overflow用户
提问于 2012-12-20 05:46:45
回答 1查看 2.4K关注 0票数 6

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

代码语言:javascript
复制
[task setCurrentDirectoryPath:@"....."];
[task setArguments:];

我只需要写一些数据

代码语言:javascript
复制
NSString * message = @"Hello World";
[stdinHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];

并在另一个线程上接收此消息

代码语言:javascript
复制
NSData *stdOutData = [reader availableData];
NSString * message = [NSString stringWithUTF8String:[stdOutData bytes]]; //My Hello World

例如,在C#中,使用NamedPipeClientStream和NamedPipeServerStream类可以很容易地完成这些事情,其中管道是通过id字符串注册的。

如何在Objective-C中实现它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-20 06:52:35

如果我没理解错的话,你可以创建一个NSPipe,一端用于读取,另一端用于写入。示例:

代码语言:javascript
复制
// 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];
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13961799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档