Created
November 23, 2013 16:43
-
-
Save katsuhide/7616857 to your computer and use it in GitHub Desktop.
コマンドの実行
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
NSTask *task = [[NSTask alloc] init]; | |
// 標準出力用 | |
NSPipe *outPipe = [NSPipe pipe]; | |
[task setStandardOutput:outPipe]; | |
// 標準エラー用 | |
// 標準出力用と同じNSPipeをsetしても良いけど、分けておくと結果がエラーになったかどうかが分かる。 | |
NSPipe *errPipe = [NSPipe pipe]; | |
[task setStandardError:errPipe]; | |
// command create | |
NSString *command = @"/bin/sleep"; | |
NSString *argument = @"3"; | |
[task setLaunchPath:command]; | |
[task setArguments:arguments]; | |
// ここでコマンドの実行 | |
// コマンドが終了するのを待たずに、すぐに処理が返ってくる | |
[task launch]; | |
// コマンドの結果を取得 | |
// readDataToEndOfFile によって、実行が終了するまで待ってくれる。 | |
// コマンドの実行結果に応じて、標準出力と標準エラーのどちらかにデータが入っている。 | |
NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile]; | |
if (data != nil && [data length]) | |
{ | |
NSString *strOut = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
NSLog(@"%@", strOut); | |
} | |
data = [[errPipe fileHandleForReading] readDataToEndOfFile]; | |
if (data != nil && [data length]) | |
{ | |
NSString *strErr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
NSLog(@"ERROR:%@", strErr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment