How to run NSTask with multiple commands

后端 未结 3 552
感动是毒
感动是毒 2021-01-01 04:08

I\'m trying to make a NSTask running a command like this:

ps -clx | grep \'Finder\' | awk \'{print $2}\'

Here is my method

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 04:30

    The following code works for me.

    NSTask *task1 = [[NSTask alloc] init];
    NSPipe *pipe1 = [NSPipe pipe];
    [task1 waitUntilExit];
    [task1 setLaunchPath: @"/bin/sh"];
    [task1 setArguments: [NSArray arrayWithObjects: @"-c",@"ps -A |grep -m1 Finder | awk '{print $1}'", nil]];
    [task1 setStandardOutput: pipe1];
    [task1 launch];
    
    NSFileHandle *file = [pipe1 fileHandleForReading];
    NSData * data = [file readDataToEndOfFile];
    
    NSString * string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog(@"Result: %@", string);
    

提交回复
热议问题