Cocoa newbie warning!
I find the following shell command to be a nice way to determine if a process is running (1 = running, 0 = not running):
if [ $(ps -Ac | egrep -o 'ProcessName') ]; then echo 1; else echo 0; fi;
I can incorporate this into Cocoa with the “system” command:
system("if [ $(ps -Ac | egrep -o 'Finder') ]; then echo 1; else echo 0; fi;");
However, the output is directed to the run log, and I can’t figure out how to capture the result (1 or 0) in my Cocoa code.
I tried implementing this with NSTask as follows:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:[NSArray arrayWithObject:@"if [ $(ps -Ac | egrep -o 'Finder') ]; then echo 1; else echo 0; fi;"]];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
[task launch];
NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
[task waitUntilExit];
[task release];
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog (@"%@", output);
[output release];
However, this generates the following error message:
if [ $(ps -Ac | egrep -o ‘Finder’) ]; then echo 1; else echo 0; fi;: No such file or directory
Can you please tell me how I can correctly implement this shell command in a way that allows me to capture the output (1 or 0) in code? (I am aware of other methods of determining whether a process is running, but part of the reason for my question is to learn how to implement shell scripts in general within Cocoa.)
Thank you very much for any help with this problem.
Rob, thank you for the general pointer about using a direct solution in code whenever possible. I looked through JongAm Park’s wrapper for
sysctl, as well as Apple’spssource code. It will take a while to incorporate, but I know now where to look for a direct solution to getting a list of processes.shellter and tripleee, thank you for your suggestions concerning interacting with shell commands. Based on your suggestions, I got three methods to work (!):
Method 1 uses the
systemcommand’s return code (no need foregrep -o):Method 2 uses NSTask with the shell
-coption (note-crather than-e):Method 3 also uses NSTask with the shell
-coption, but in this case, the command to be executed is another shell with its own-coption (this was the only way I could find after much trial and error to incorporate anifconstruct in the command to be executed; of course, it is way overkill for the current problem):Thank you all for the wonderful help.