Last active
January 22, 2024 13:23
-
-
Save xaviervia/6087296 to your computer and use it in GitHub Desktop.
Reading the output from a shell command in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ay thanks!