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.