LoginSignup
13
14

More than 5 years have passed since last update.

UNIXコマンドを実行する(同期)

Posted at

アプリからUNIXコマンドを実行する。
同期処理で実行する場合。

Objective-C
- (IBAction)doAction:(id)sender
{
    NSTask *task = [[[NSTask alloc] init] autorelease];

    // 標準出力用
    NSPipe *outPipe = [NSPipe pipe];
    [task setStandardOutput:outPipe];

    // 標準エラー用
    // 標準出力用と同じNSPipeをsetしても良いけど、分けておくと結果がエラーになったかどうかが分かる。
    NSPipe *errPipe = [NSPipe pipe];
    [task setStandardError:errPipe];

    // user$ man ls を実行してみる
    [task setLaunchPath:@"/usr/bin/man"];
    [task setArguments:[NSArray arrayWithObjects:@"ls", nil]];

    // user$ ls -la でDesktopのファイルを一覧する場合はこんな感じ
//  [task setCurrentDirectoryPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"]];
//  [task setLaunchPath:@"/bin/ls"];
//  [task setArguments:[NSArray arrayWithObjects:@"-la", nil]];

    // ここでコマンドの実行
    // コマンドが終了するのを待たずに、すぐに処理が返ってくる
    [task launch];

    // コマンドの結果を取得
    // readDataToEndOfFile によって、実行が終了するまで待ってくれる。
    // コマンドの実行結果に応じて、標準出力と標準エラーのどちらかにデータが入っている。
    NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile];
    if (data != nil && [data length])
    {
        NSString *strOut = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"%@", strOut);
    }

    data = [[errPipe fileHandleForReading] readDataToEndOfFile];
    if (data != nil && [data length])
    {
        NSString *strErr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"ERROR:%@", strErr);
    }
}
13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14