首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取NSRunningApplication的参数?

如何获取NSRunningApplication的参数?
EN

Stack Overflow用户
提问于 2022-05-31 07:46:20
回答 1查看 116关注 0票数 2

如何获得NSRunningApplication启动期间使用的参数列表,类似于运行ps aux时看到的

代码语言:javascript
复制
let workspace = NSWorkspace.shared
let applications = workspace.runningApplications

for application in applications {
    // how do I get arguments that were used during application launch?
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-31 09:31:36

"ps“工具使用sysctl()KERN_PROCARGS2来获取正在运行的进程的参数。下面是将代码从cmds-153/ps/print.c转换为Swift的尝试。该文件还包含原始参数空间的内存布局的文档,并解释了如何在该内存中定位字符串参数。

代码语言:javascript
复制
func processArguments(pid: pid_t) -> [String]? {
    
    // Determine space for arguments:
    var name : [CInt] = [ CTL_KERN, KERN_PROCARGS2, pid ]
    var length: size_t = 0
    if sysctl(&name, CUnsignedInt(name.count), nil, &length, nil, 0) == -1 {
        return nil
    }
    
    // Get raw arguments:
    var buffer = [CChar](repeating: 0, count: length)
    if sysctl(&name, CUnsignedInt(name.count), &buffer, &length, nil, 0) == -1 {
        return nil
    }
    
    // There should be at least the space for the argument count:
    var argc : CInt = 0
    if length < MemoryLayout.size(ofValue: argc) {
        return nil
    }
    
    var argv: [String] = []
    
    buffer.withUnsafeBufferPointer { bp in
        
        // Get argc:
        memcpy(&argc, bp.baseAddress, MemoryLayout.size(ofValue: argc))
        var pos = MemoryLayout.size(ofValue: argc)
        
        // Skip the saved exec_path.
        while pos < bp.count && bp[pos] != 0 {
            pos += 1
        }
        if pos == bp.count {
            return
        }
        
        // Skip trailing '\0' characters.
        while pos < bp.count && bp[pos] == 0 {
            pos += 1
        }
        if pos == bp.count {
            return
        }
        
        // Iterate through the '\0'-terminated strings.
        for _ in 0..<argc {
            let start = bp.baseAddress! + pos
            while pos < bp.count && bp[pos] != 0 {
                pos += 1
            }
            if pos == bp.count {
                return
            }
            argv.append(String(cString: start))
            pos += 1
        }
    }
    
    return argv.count == argc ? argv : nil
}

只有一个简单的错误处理:如果有任何问题,该函数返回nil

对于NSRunningApplication的一个实例,您可以调用

代码语言:javascript
复制
processArguments(pid: application.processIdentifier)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72443976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档