Created
March 2, 2024 21:20
-
-
Save stephancasas/eb158c3bd5743b5ef0a598a633b4b312 to your computer and use it in GitHub Desktop.
How 'bout I do anyway? π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ProcessSerialNumber.swift | |
// | |
// Created by Stephan Casas on 2/28/24. | |
// | |
extension ProcessSerialNumber { | |
/// Create a new `ProcessSerialNumber` using the given process identifier. | |
init?(_ pid: pid_t) { | |
var psn = ProcessSerialNumber( | |
highLongOfPSN: 0, | |
lowLongOfPSN: 0); | |
guard ProcessSerialNumber.getProcessForPid( | |
pid, &psn | |
) == .zero else { | |
return nil; | |
} | |
self = psn; | |
} | |
/// Alias to the deprecated-but-still-widely-used `GetProcessForPID` function. | |
static func getProcessForPid( | |
_ pid: pid_t, | |
_ psn: UnsafeMutablePointer<ProcessSerialNumber> | |
) -> OSStatus { | |
guard | |
let HIServicesFramework = dlopen( | |
"/System/Library/Frameworks/ApplicationServices.framework/Frameworks/HIServices.framework/HIServices", | |
RTLD_NOW), | |
let $GetProcessForPID = dlsym( | |
HIServicesFramework, | |
"GetProcessForPID") | |
else { | |
return 1; | |
} | |
return unsafeBitCast( | |
$GetProcessForPID, | |
to: (@convention(c) ( | |
pid_t, | |
UnsafeMutablePointer<ProcessSerialNumber> | |
) -> OSStatus).self | |
)(pid, psn); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment