Skip to content

Instantly share code, notes, and snippets.

@godrm
Created September 19, 2019 04:40
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 godrm/f84bc6e1ee9d63e338fd8bb950a83954 to your computer and use it in GitHub Desktop.
Save godrm/f84bc6e1ee9d63e338fd8bb950a83954 to your computer and use it in GitHub Desktop.
#import <Carbon/Carbon.h>
#import <dlfcn.h>
/*
* 컴파일 명령 : gcc process.c -framework CoreServices
*/
CFArrayRef CopyLaunchedApplicationsInFrontToBackOrder(void)
{
CFArrayRef (*_LSCopyApplicationArrayInFrontToBackOrder)(uint32_t sessionID) = NULL;
void (*_LSASNExtractHighAndLowParts)(void const* asn, UInt32* psnHigh, UInt32* psnLow) = NULL;
CFTypeID (*_LSASNGetTypeID)(void) = NULL;
void *lsHandle = dlopen("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/LaunchServices", RTLD_LAZY);
if (!lsHandle) { return NULL; }
_LSCopyApplicationArrayInFrontToBackOrder = (CFArrayRef(*)(uint32_t))dlsym(lsHandle, "_LSCopyApplicationArrayInFrontToBackOrder");
_LSASNExtractHighAndLowParts = (void(*)(void const*, UInt32*, UInt32*))dlsym(lsHandle, "_LSASNExtractHighAndLowParts");
_LSASNGetTypeID = (CFTypeID(*)(void))dlsym(lsHandle, "_LSASNGetTypeID");
if (_LSCopyApplicationArrayInFrontToBackOrder == NULL || _LSASNExtractHighAndLowParts == NULL || _LSASNGetTypeID == NULL) { return NULL; }
CFMutableArrayRef orderedApplications = CFArrayCreateMutable(kCFAllocatorDefault, 64, &kCFTypeArrayCallBacks);
if (!orderedApplications) { return NULL; }
CFArrayRef apps = _LSCopyApplicationArrayInFrontToBackOrder(-1);
if (!apps) { CFRelease(orderedApplications); return NULL; }
CFIndex count = CFArrayGetCount(apps);
for (CFIndex i = 0; i < count; i++)
{
ProcessSerialNumber psn = {0, kNoProcess};
CFTypeRef asn = CFArrayGetValueAtIndex(apps, i);
if (CFGetTypeID(asn) == _LSASNGetTypeID())
{
_LSASNExtractHighAndLowParts(asn, &psn.highLongOfPSN, &psn.lowLongOfPSN);
printf("%ld, ", psn.lowLongOfPSN);
}
}
CFRelease(apps);
CFArrayRef result = CFArrayGetCount(orderedApplications) == 0 ? NULL : CFArrayCreateCopy(kCFAllocatorDefault, orderedApplications);
CFRelease(orderedApplications);
return result;
}
int main() {
CopyLaunchedApplicationsInFrontToBackOrder();
/*
* 실행 결과 예시 - 화면 순서별 프로세스 id
635035, 2175507, 3748755, 364633, 3847083, 3556196, 3974090, 3961799, 1323331, 81940, 3584875, 905437
*/
}
/*
* 백그라운드 제외한 프로세스 목록 (이름, id)
osascript -e 'tell application "System Events" to get {name, id} of (processes where background only is false)'
Finder, Safari, iTerm2, Sourcetree, Music, Slack, Airmail 3, Telegram, Script Editor, Xcode, Preview, Activity Monitor, 81940, 364633, 635035, 905437, 1323331, 2175507, 3556196, 3584875, 3748755, 3847083, 3961799, 3974090
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment