How to Identify if the process in User Interface Process?

后端 未结 3 1271
执笔经年
执笔经年 2021-01-15 15:47

How can I get information from a process that it is UI(User Interface) process or non-ui?

With UI process I mean, Finder, Dock, System UI server, or any other mac a

3条回答
  •  醉梦人生
    2021-01-15 16:46

    There is no way to determine based purely on the PID number what a specific process is. The reason for this: Process IDs are assigned (somewhat) sequentially from PID=1 on startup, and startup can be different for different systems. The process ID will also be reassigned if, for example, Finder or Dock crashes and has to be restarted.

    If you can run a terminal command with a specific pid that you have, though, do this:

    ps -p  -o ucomm=
    

    You'll get the filename of the process, which you can check against a list of ones you know are UI processes. For example, here is the output of certain ps commands on my system for my current login session:

    > ps -p 110 -o ucomm=
    Dock
    
    > ps -p 112 -o ucomm=
    Finder
    

    And the following command will give you a list of processes in order of process ID, with only the name:

    > ps -ax -o pid=,ucomm=
       1 launchd
      10 kextd
      11 DirectoryService
         ...
    

    EDIT: You may be able to do what you ask, though it is convoluted. This answer mentions:

    The function CGWindowListCopyWindowInfo() from CGWindow.h will return an array of dictionaries, one for each window that matches the criteria you set, including ones in other applications. It only lets you filter by windows above a given window, windows below a given window and 'onscreen' windows, but the dictionary returned includes a process ID for the owning app which you can use to match up window to app.

    If you can obtain all the CGWindows and their respective pids, then you will know the pids of all UI applications without needing to run ps at all.

    Rahul has implemented the following code for this approach, which he requested I add to my answer:

    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;
    }
    

提交回复
热议问题