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.
echo 1to work. Also because of the ` No such file or directory` msg, that the system() called directly to the local dir, looking for a file nameif .... I'm guess that you need to wrap your 'script' with the path to the shell AND-e(execute option?) of the shell, producing the simple case test[task setArguments:[NSArray arrayWithObject:@"/bin/bash -e 'echo 1'"]]. Why not just use your code to call scripts saved to your filesystem? Good luck.system()you'd use something likesystem("sh -c 'echo moo'"). You are better off just capturing the result code fromsystem()rather than the command's output, and then you don't need theifand theechos:system("sh -c 'ps -Ac | egrep -o Finder'")and the exit code fromegrepwill be returned, indicating whether or not there was a match.