我试图做一个NSTask运行如下命令:如何使用多个命令运行NSTask
PS -clx | grep'Finder'| AWK '{打印$ 2}'
这里是我的方法
- (void) processByName:(NSString*)name {
NSTask *task1 = [[NSTask alloc] init];
NSPipe *pipe1 = [NSPipe pipe];
[task1 waitUntilExit];
[task1 setLaunchPath: @"/bin/ps"];
[task1 setArguments: [NSArray arrayWithObjects: @"-clx", nil]];
[task1 setStandardOutput: pipe1];
NSTask *task2 = [[NSTask alloc] init];
NSPipe *pipe2 = [NSPipe pipe];
[task2 setLaunchPath: @"/usr/bin/grep"];
[task2 setArguments: [NSArray arrayWithObjects: @"'Finder'", nil]];
[task2 setStandardInput:pipe1];
[task2 setStandardOutput: pipe2];
NSTask *task3 = [[NSTask alloc] init];
NSPipe *pipe3 = [NSPipe pipe];
[task3 setLaunchPath: @"/usr/bin/grep"];
[task3 setArguments: [NSArray arrayWithObjects: @"'{print $2}'", nil]];
[task3 setStandardInput:pipe2];
[task3 setStandardOutput: pipe3];
NSFileHandle *file = [pipe3 fileHandleForReading];
[task1 launch];
[task2 launch];
[task3 launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Result: %@", string);
}
但结果只是
结果:
我在做什么错?
编辑
- (void) processByName:(NSString*)name {
NSTask *task1 = [[NSTask alloc] init];
NSPipe *pipe1 = [NSPipe pipe];
[task1 waitUntilExit];
[task1 setLaunchPath: @"/bin/ps"];
[task1 setArguments: [NSArray arrayWithObjects: @"-clx", nil]];
[task1 setStandardOutput: pipe1];
NSTask *task2 = [[NSTask alloc] init];
NSPipe *pipe2 = [NSPipe pipe];
[task2 setLaunchPath: @"/usr/bin/grep"];
[task2 setArguments: [NSArray arrayWithObjects: @"'Finder'", nil]];
[task2 setStandardInput:pipe1];
[task2 setStandardOutput: pipe2];
NSTask *task3 = [[NSTask alloc] init];
NSPipe *pipe3 = [NSPipe pipe];
[task3 setLaunchPath: @"/usr/bin/grep"];
[task3 setArguments: [NSArray arrayWithObjects: @"'{print $2}'", nil]];
[task3 setStandardInput:pipe2];
[task3 setStandardOutput: pipe3];
NSFileHandle *file = [pipe3 fileHandleForReading];
[task1 launch];
[task2 launch];
[task3 launch];
[[NSNotificationCenter defaultCenter] addObserverForName:NSTaskDidTerminateNotification
object:task3
queue:nil
usingBlock:^(NSNotification* notification){
NSData * data = [file readDataToEndOfFile];
NSString * string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Result: %@", string);
}];
}
在附加观察者之后启动任务会更有意义吗?如果任务在观察者被连接之前完成,该怎么办? – eonist 2016-12-16 12:58:23