user3564870 user3564870 - 14 days ago 8
Objective-C Question

Given a Process ID, determine if the process is a windowed process on a Mac

Need a way to programmatically determine if a process is a windowed process using the process ID. This needs to work for both user and system processes.

With the crude method below, one could determine if a user process is windowed. However, this has a major flaw, it will only work for user processes, not system.

- (BOOL)processIsWindowed:(pid_t)processID {
for (NSRunningApplication app in [[NSWorkspace sharedWorkspace] runningApplications]) {
if(app.processIdentifier == processID && (app.activationPolicy == NSApplicationActivationPolicyRegular)){
return YES;
}
}
return NO;
}


Using:

static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount){}


from
Using NSWorkspace to get all running processes

will list all processes, but I can't immediatgely see a way to determine if it is a windowed process.

A process listed by the above method has flags
(i.e. process->kp_proc.p_flags)
but I don't see any flags listed: https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/proc.h that might indicate it as a windowed process.

Answer

Here's how you can determine if a process has a window:

The UiProcesses() method will create an array of processIDs for processes with windows.

CFArrayRef UiProcesses()
{
    CFArrayRef  orderedwindows = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
    CFIndex count = CFArrayGetCount (orderedwindows);
    CFMutableArrayRef uiProcess = CFArrayCreateMutable (kCFAllocatorDefault , count,  &kCFTypeArrayCallBacks);
    for (CFIndex i = 0; i < count; i++)
    {
        if (orderedwindows)
        {
            CFDictionaryRef windowsdescription = (CFDictionaryRef)CFArrayGetValueAtIndex(orderedwindows, i);
            CFNumberRef windowownerpid  = (CFNumberRef)CFDictionaryGetValue (windowsdescription, CFSTR("kCGWindowOwnerPID"));
            CFArrayAppendValue (uiProcess, windowownerpid);

        }
    }
    return uiProcess;
}

Source: How to Identify if the process in User Interface Process?