Skip to content

Instantly share code, notes, and snippets.

@stephancasas
Created March 2, 2024 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephancasas/eb158c3bd5743b5ef0a598a633b4b312 to your computer and use it in GitHub Desktop.
Save stephancasas/eb158c3bd5743b5ef0a598a633b4b312 to your computer and use it in GitHub Desktop.
How 'bout I do anyway? πŸ˜’
//
// 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