views:

409

answers:

4

Is there any Carbon/Cocoa/C API available on Macs that I can use to enumerate processes? I'm looking for something like EnumProcesses on Windows.

My goal is to check from code whether a process is running (by name).

Thanks!

+3  A: 

There are a couple ways you can do this:

  1. If it's a GUI app with a Dock icon, use -[NSWorkspace launchedApplications].
  2. Fork off another process (like ps or top or whatever) via an NSTask, read the results, and search yourself (or pipe it through grep or something).
  3. Use the GetBSDProcessList function described here: http://developer.apple.com/mac/library/qa/qa2001/qa1123.html (I've used this successfully in the past)
Dave DeLong
+1  A: 

Ah, I just found the Process Manager reference

Looks like GetNextProcess and GetProcessInfo help in figuring out what's running. As suggested by Dave, GetBSDProcessList can be used if you're looking for daemons and not just Carbon/Cocoa processes.

psychotik
You may not want to use these older functions as Apple may choose to depreciate them. Cocoa classes are generally safer in this respect.
ericgorr
FYI, `GetBSDProcessList` is *much* faster than iterating through the Process Manager yourself.
Dave DeLong
The Process Manager is not (currently) deprecated and is available in 64-bit. I don't think it has an axe over its head the way some of the other APIs have.
Peter Hosey
This does seem to be best documented of all the options above, and I don't see any notes regarding deprecation. For a one-time check of running processes from any Carbon/Cocoa app (not just Dock apps), this seems ideal even if it might be slower than other options.
psychotik
no deprecation yet, runningApplications being 10.6 only these look great
valexa
+1  A: 

In the overview of the NSRunningApplicationClass, it says:

NSRunningApplication is a class to manipulate and provide information for a single instance of an application. Only user applications are tracked; this does not provide information about every process on the system.

and

To access the list of all running applications, use the runningApplications method in NSWorkspace.

I would suggest taking a look at Workspace Services Programming Topics

ericgorr
Those are great, if you can limit yourself to GUI apps on 10.6
Dave DeLong
A: 

I am using this code:

+ (BOOL)isAppRunning:(NSString*)appName {
    BOOL ret = NO;
    ProcessSerialNumber psn = { kNoProcess, kNoProcess };
    while (GetNextProcess(&psn) == noErr) {
        CFDictionaryRef cfDict = ProcessInformationCopyDictionary(&psn,  kProcessDictionaryIncludeAllInformationMask);
        if (cfDict) {
            NSString *name = [(NSDictionary *)cfDict objectForKey:(id)kCFBundleNameKey];
            if (name) {
                if ([appName isEqualToString:name]) {
                    ret = YES;
                }
            }
            CFRelease(cfDict);          
        }
    }
    return ret;
}
valexa