You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS的Launch Daemon中枚举所有已登录用户会话?

在Launch Daemon中枚举所有已登录用户的会话ID

你可以通过以下两种常用方式在Launch Daemon中获取当前所有已登录用户的会话ID:

方法一:使用utmpx标准Unix API

这是跨Unix平台的通用方法,能遍历系统中所有登录会话:

#include <utmpx.h>
#include <stdio.h>

void enumerate_all_sessions() {
    struct utmpx *entry;
    // 初始化utmpx遍历
    setutxent();
    
    while ((entry = getutxent()) != NULL) {
        // 仅筛选用户登录进程对应的会话
        if (entry->ut_type == USER_PROCESS) {
            printf("用户名: %s, 会话ID: %d\n", entry->ut_user, entry->ut_session);
        }
    }
    
    // 结束遍历,释放资源
    endutxent();
}

方法二:使用CoreGraphics框架的会话API

这是macOS专属方法,能获取更详细的GUI会话信息,适合需要关联图形会话的场景:

#import <CoreGraphics/CoreGraphics.h>

void enumerate_cgs_sessions() {
    // 获取所有会话属性数组
    CFArrayRef allSessions = CGSSessionCopyAllSessionProperties();
    if (!allSessions) return;
    
    CFIndex sessionCount = CFArrayGetCount(allSessions);
    for (CFIndex i = 0; i < sessionCount; i++) {
        CFDictionaryRef sessionProps = CFArrayGetValueAtIndex(allSessions, i);
        
        // 提取会话ID和用户名
        CFNumberRef sessionID = CFDictionaryGetValue(sessionProps, kCGSSessionIDKey);
        CFStringRef userName = CFDictionaryGetValue(sessionProps, kCGSSessionUserNameKey);
        
        if (sessionID && userName) {
            int idValue;
            CFNumberGetValue(sessionID, kCFNumberIntType, &idValue);
            
            char userNameCStr[256];
            CFStringGetCString(userName, userNameCStr, sizeof(userNameCStr), kCFStringEncodingUTF8);
            
            printf("用户名: %s, 会话ID: %d\n", userNameCStr, idValue);
        }
    }
    
    CFRelease(allSessions);
}

注意事项

  • 编译使用CoreGraphics的代码时,需要链接对应框架,例如在clang编译时添加参数:-framework CoreGraphics
  • Launch Daemon以root权限运行,默认可以访问这些会话信息,无需额外权限配置

内容的提问来源于stack exchange,提问作者c00000fd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:45:13