简体   繁体   English

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

[英]Communication between process using NSPipe,NSTask

I need to realize a communication between two threads using NSPipe channels, the problem is that I don't need to call terminal command by specifying this methods. 我需要使用NSPipe通道实现两个线程之间的通信,问题是我不需要通过指定此方法来调用terminal命令。

[task setCurrentDirectoryPath:@"....."];
[task setArguments:];

I just need to write some data 我只需要写一些数据

NSString * message = @"Hello World";
[stdinHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];

and on the other thread to receive this message 并在另一个线程上接收此消息

NSData *stdOutData = [reader availableData];
NSString * message = [NSString stringWithUTF8String:[stdOutData bytes]]; //My Hello World

For example such things in C# can be easy done with NamedPipeClientStream, NamedPipeServerStream classes where pipes are registered by id string. 例如,使用NamedPipeClientStream,NamedPipeServerStream类可以轻松完成C#中的这些操作,其中管道由id字符串注册。

How to achieve it in Objective-C? 如何在Objective-C中实现它?

If I understand your question correctly, you can just create a NSPipe and use one end for reading and one end for writing. 如果我正确理解了您的问题,您可以创建一个NSPipe并使用一端进行读取,一端用于写入。 Example: 例:

// 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM