macos - 获取从另一个用户运行的应用程序的包标识符

标签 macos nsworkspace sysctl cfbundleidentifier nsrunningapplication

场景是这样的:“我从一个用户运行一个应用程序(例如 myproc),然后快速用户切换到第二个用户”
现在,当我尝试确定使用特定包标识符(例如 com.ak.myproc)运行的所有进程时;我无法确定从第一个用户运行的进程的情况。

我尝试了以下方法,但没有成功:

  1. [NSRunningApplication runningApplicationsWithBundleIdentifier:]
  2. [[NSWorkspace sharedWorkspace] runningApplications],然后比较每个应用程序的包标识符 - 为第一个用户运行的应用程序甚至不会显示在此列表中。
  3. 使用sysctl(),然后迭代进程列表 - 这里,第一个用户的应用程序的 pid 确实出现了。在那之后:
    • 当我尝试 [NSRunningApplication runningApplicationWithProcessIdentifier:] 时,我得到了 nil。
    • 当我尝试 GetProcessForPID()ProcessInformationCopyDictionary() 时,我得到了一个 nil 字典。
    • 当我尝试 GetProcessForPID()GetProcessInformation() 时,我在 ProcessInfoRec 中没有得到任何有用的信息。

有人可以帮忙吗?谢谢。

操作系统:Mac OS X 10.8.4
Xcode:4.6.2

最佳答案

您可以使用NSWorkspace将进程名称映射到包ID。

#include <sys/sysctl.h>
#include <pwd.h>
typedef struct kinfo_proc kinfo_proc;
static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
// Returns a list of all BSD processes on the system.  This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount.  You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
{
    int                 err;
    kinfo_proc *        result;
    bool                done;
    static const int    name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
    // Declaring name as const requires us to cast it when passing it to
    // sysctl because the prototype doesn't include the const modifier.
    size_t              length;

    //    assert( procList != NULL);
    //    assert(*procList == NULL);
    //    assert(procCount != NULL);

    *procCount = 0;

    // We start by calling sysctl with result == NULL and length == 0.
    // That will succeed, and set length to the appropriate length.
    // We then allocate a buffer of that size and call sysctl again
    // with that buffer.  If that succeeds, we're done.  If that fails
    // with ENOMEM, we have to throw away our buffer and loop.  Note
    // that the loop causes use to call sysctl with NULL again; this
    // is necessary because the ENOMEM failure case sets length to
    // the amount of data returned, not the amount of data that
    // could have been returned.

    result = NULL;
    done = false;
    do {
        assert(result == NULL);

        // Call sysctl with a NULL buffer.

        length = 0;
        err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
                     NULL, &length,
                     NULL, 0);
        if (err == -1) {
            err = errno;
        }

        // Allocate an appropriately sized buffer based on the results
        // from the previous call.

        if (err == 0) {
            result = malloc(length);
            if (result == NULL) {
                err = ENOMEM;
            }
        }

        // Call sysctl again with the new buffer.  If we get an ENOMEM
        // error, toss away our buffer and start again.

        if (err == 0) {
            err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
                         result, &length,
                         NULL, 0);
            if (err == -1) {
                err = errno;
            }
            if (err == 0) {
                done = true;
            } else if (err == ENOMEM) {
                assert(result != NULL);
                free(result);
                result = NULL;
                err = 0;
            }
        }
    } while (err == 0 && ! done);

    // Clean up and establish post conditions.

    if (err != 0 && result != NULL) {
        free(result);
        result = NULL;
    }
    *procList = result;
    if (err == 0) {
        *procCount = length / sizeof(kinfo_proc);
    }

    assert( (err == 0) == (*procList != NULL) );

    return err;
}

+ (NSArray*)getBSDProcessList
{
    kinfo_proc *mylist =NULL;
    size_t mycount = 0;
    GetBSDProcessList(&mylist, &mycount);

    NSMutableArray *processes = [NSMutableArray arrayWithCapacity:(int)mycount];

    for (int i = 0; i < mycount; i++) {
        struct kinfo_proc *currentProcess = &mylist[i];
        struct passwd *user = getpwuid(currentProcess->kp_eproc.e_ucred.cr_uid);
        NSMutableDictionary *entry = [NSMutableDictionary dictionaryWithCapacity:4];

        NSNumber *processID = [NSNumber numberWithInt:currentProcess->kp_proc.p_pid];
        NSString *processName = [NSString stringWithFormat: @"%s",currentProcess->kp_proc.p_comm];
        if (processID)[entry setObject:processID forKey:@"processID"];
        if (processName)[entry setObject:processName forKey:@"processName"];
        if (processName)
        {
            NSString *bunldeID = [self bundleIdentifierForApplicationName:processName];
            if (bunldeID)
                [entry setObject:bunldeID forKey:@"bundleId"];
        }
        if (user){
            NSNumber *userID = [NSNumber numberWithUnsignedInt:currentProcess->kp_eproc.e_ucred.cr_uid];
            NSString *userName = [NSString stringWithFormat: @"%s",user->pw_name];

            if (userID)[entry setObject:userID forKey:@"userID"];
            if (userName)[entry setObject:userName forKey:@"userName"];
        }
        [processes addObject:[NSDictionary dictionaryWithDictionary:entry]];
    }
    free(mylist);

    return [NSArray arrayWithArray:processes];
}
+ (NSString *) bundleIdentifierForApplicationName:(NSString *)appName
{
    NSWorkspace * workspace = [NSWorkspace sharedWorkspace];
    NSString * appPath = [workspace fullPathForApplication:appName];
    if (appPath) {
        NSBundle * appBundle = [NSBundle bundleWithPath:appPath];
        return [appBundle bundleIdentifier];
    }
    return nil;
}

关于macos - 获取从另一个用户运行的应用程序的包标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855995/

相关文章:

objective-c - 如何检查 Finder 是否将具有给定扩展名的目录显示为包?

swift - NSWorkspace.OpenConfiguration 忽略参数,尽管没有被沙箱化

objective-c - NSWorkspace选择文件:inFileViewerRootedAtPath: does not work the first time it is called

linux-kernel - 需要根据我自己的服务器需要 "calculate"最佳 ulimit 和 fs.file-max 值

c++ - 在 macOS 中使用 omp.h 的正确方法

python - 导入错误 : No module named 'Cython' when installing Cython on mac for darkflow

node.js - 在Mac上运行 'bower install'

git - `git -S -m commit` 请求密码失败 — 从 GPG mac 移动到 GPG shell 后签名

linux - 如果设备是 ext4,如何将 block 号映射到 vm.block_dump=1 产生的 dmesg 输出中的文件名?

ubuntu - ubuntu 中的 CPUSTATES uint64_ts (user, nice, sys, intr, idle) 数组