如何獲取在啟動期間使用的引數串列 a NSRunningApplication
,類似于我在運行時看到的引數串列ps aux
:
let workspace = NSWorkspace.shared
let applications = workspace.runningApplications
for application in applications {
// how do I get arguments that were used during application launch?
}
uj5u.com熱心網友回復:
“ps”工具使用sysctl()
withKERN_PROCARGS2
來獲取正在運行的行程的引數。以下是將代碼從adv_cmds-153/ps/print.c 轉換為 Swift 的嘗試。該檔案還包含原始引數空間的記憶體布局的檔案,并解釋了如何在該記憶體中定位字串引數。
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
您可以呼叫
processArguments(pid: application.processIdentifier)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483968.html