使用NSPipe,NSTask进程之间的通信

时间:2012-12-19 21:46:45

标签: objective-c ipc nstask nspipe

我需要使用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

例如,使用NamedPipeClientStream可以轻松完成c#中的这些操作, NamedPipeServerStream类,其中管道由id字符串注册。

如何在Objective-C中实现它?

1 个答案:

答案 0 :(得分: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];
}