I\'m trying to make a NSTask running a command like this:
ps -clx | grep \'Finder\' | awk \'{print $2}\'
Here is my method
The tasks run in a separate process from your code, i.e., asychronously. They probably haven't finished (they may not have even launched!) by the time you get to the readDataToEndOfFile
two lines later.
If you're already on a background thread here, you can poll their status: while( ![task isRunning]){
, or if you're on the main thread, I'd suggest using GCD to put this onto a queue and doing the polling there.
Actually, better than that would be to use notifications:
[task3 launch];
[[NSNotificationCenter defaultCenter] addObserverForName:NSTaskDidTerminateNotification
object:task3
queue:nil
usingBlock:^{
NSData * data = [file readDataToEndOfFile];
NSString * string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Result: %@", string);
}];
See TN2050: Observing Process Lifetime Without Polling. Each NSTask
will send NSTaskDidTerminateNotification
when it terminates (you should, ideally, check its return code rather than assuming it ran successfully). You can create a block to be run when task3
sends that notification.
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);
Almost 8 years later, I think grep binary is'nt in /usr/bin, for me it's in /bin. Also, for your awk command, you set the launch path to grep.