objective-cipcnstasknspipe

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.

[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.

How to achieve it in Objective-C?


Solution

  • If I understand your question correctly, you can just create a NSPipe and use one end for reading and one end for writing. 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];
    }