- Inherits from:
- NSObject
- Conforms to:
- NSObject
- (NSObject)
Declared in:
- Foundation/NSFileHandle.h
NSPipe objects provide an object-oriented interface for accessing pipes. A pipe is a one-way communications channel between related processes; one process writes data while the other process reads the data.
An NSPipe represents both ends of a pipe and enables communication through the pipe. A pipe is a one-way communications channel between related processes; one process writes data while the other process reads that data. The data that passes through the pipe is buffered; the size of the buffer is determined by the underlying operating system.
Each end point of the pipe is a file descriptor, represented by an NSFileHandle. You thus use NSFileHandle messages to read and write pipe data. A "parent" process creates the NSPipe and holds one end of it. It creates an NSTask for the other process and, before launching it, passes the other end of the pipe to that process; it does this by setting the NSTask's standard input, standard output, or standard error device to be the other NSFileHandle or the NSPipe itself (in the latter case, the type of NSFileHandle-reading or writing-is determined by the NSTask "set" method).
The following example illustrates the above procedure:
- (void)readTaskData:(id)sender { NSTask *pipeTask = [[NSTask alloc] init]; NSPipe *newPipe = [NSPipe pipe]; NSFileHandle *readHandle = [newPipe fileHandleForReading]; NSData *inData = nil; [pipeTask setStandardOutput:newPipe]; // write handle is closed to this process [pipeTask setLaunchPath:[NSHomeDirectory() stringByAppendingPathComponent:@"PipeTask.app/PipeTask"]]; [pipeTask launch]; while ((inData = [readHandle availableData]) && [inData length]) { [inData processData]; } }
The launched process in this example must get data and write that data, using NSFileHandle's writeData:, to its standard output device (obtained NSFileHandle's fileHandleWithStandardOutput).
When the processes have no more data to communicate across the pipe, the writing process should simply send closeFile to its NSFileHandle end point. This causes the process with the "read" NSFileHandle to receive an empty NSData, signalling end of data. If the "parent" process created the NSPipe with the init method, it should then release it.
- Creating an NSPipe
- - init
- + pipe
- GettingNSFileHandles for pipe
- - fileHandleForReading
- - fileHandleForWriting
+ (id)pipe
- (NSFileHandle *)fileHandleForReading
- (NSFileHandle *)fileHandleForWriting
- (id)init
See Also: + pipe