Communication between process using NSPipe,NSTask
Asked Answered
S

1

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?

Sliest answered 19/12, 2012 at 21:46 Comment(3)
Is your question about two threads within the same process, or about separate processes that communicate via a pipe?Bazaar
Its about two threads that communicate via a pipeSliest
How can achieve separate processes that communicate via a pipe?Karakorum
B
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];
}
Bazaar answered 19/12, 2012 at 22:52 Comment(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 ?Krucik
How can i convert data to URL in the same way? Because i need continuous playback from a stream of data using AVPlayerLewendal

© 2022 - 2024 — McMap. All rights reserved.