Skip to content

Instantly share code, notes, and snippets.

@xaviervia
Last active January 22, 2024 13:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaviervia/6087296 to your computer and use it in GitHub Desktop.
Save xaviervia/6087296 to your computer and use it in GitHub Desktop.
Reading the output from a shell command in Objective-C
- (void) doIt {
// Define the command name and the arguments array (the nil at the end is needed)
NSArray *arguments = [NSArray arrayWithObjects:@"--some-argument", @"--another", nil];
NSString *command = @"do-something-shell";
// Setup the NSTask for the command execution
NSTask *task = [[NSTask alloc] init];
task.launchPath = command;
task.arguments = arguments;
// Create a NSPipe and assign the new pipe as the task's stdout
NSPipe *pipe = [NSPipe pipe];
task.standardOutput = pipe;
// Get a NSFileHandle from the pipe. This NSFileHandle will provide the stdout buffer
NSFileHandle *fileHandle = [pipe fileHandleForReading];
// Setup the current object as an Observer of the data available notification of the file handle
// We set the selector to "thereIsData:", so thereIsData will be executed when the file handle triggers the
// notification
// (this sentence is verbose)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(thereIsData:)
name:NSFileHandleDataAvailableNotification
object:fileHandle];
// Setup the file handle to work asynchronously and trigger the notification when there is data
// in the stdout
[fileHandle waitForDataInBackgroundAndNotify];
// And finally launch the task, asynchronously
[task launch];
}
// The notification will be captured and run this method,
// passing the NSFileHandle as the object property of the notification
- (void)thereIsData:(NSNotification *)notification {
NSLog(@"%@", [[NSString alloc] initWithData:[notification.object availableData] encoding:NSUTF8StringEncoding]);
[notification.object waitForDataInBackgroundAndNotify];
}
@Beyarz
Copy link

Beyarz commented Dec 5, 2018

Ay thanks!

@derekli66
Copy link

Thank you for sharing this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment