6

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?

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
Andrew
  • 885
  • 1
  • 10
  • 15

1 Answers1

4

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];
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    ok. Im confused. How does this work to allow two apps to talk to each other. And where does the pipe set some sort of identifier to share between apps ? Also how many apps could use one Pipe set ? – The Lazy Coder Oct 25 '13 at 23:38
  • How can i convert data to URL in the same way? Because i need continuous playback from a stream of data using AVPlayer – vinu Jul 30 '19 at 07:39