Skip to content

Instantly share code, notes, and snippets.

@amoe
Created March 15, 2024 13:27
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 amoe/d51c0cf1d6e08a6ff17547e83c480aa0 to your computer and use it in GitHub Desktop.
Save amoe/d51c0cf1d6e08a6ff17547e83c480aa0 to your computer and use it in GitHub Desktop.
Prevent sleep on Mac
#import <IOKit/pwr_mgt/IOPMLib.h>
// build with:
// clang -framework IOKit -framework Foundation preventsleep.c -o preventsleep
int main(int argc, char** argv) {
// kIOPMAssertionTypeNoDisplaySleep prevents display sleep,
// kIOPMAssertionTypeNoIdleSleep prevents idle sleep
// reasonForActivity is a descriptive string used by the system whenever it needs
// to tell the user why the system is not sleeping. For example,
// "Mail Compacting Mailboxes" would be a useful string.
// NOTE: IOPMAssertionCreateWithName limits the string to 128 characters.
CFStringRef reasonForActivity= CFSTR("Describe Activity Type");
IOPMAssertionID assertionID;
IOReturn success = IOPMAssertionCreateWithName(
kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn,
reasonForActivity,
&assertionID
);
if (success == kIOReturnSuccess) {
// The system is prevented from sleeping here.
sleep(3 * 60 * 60);
success = IOPMAssertionRelease(assertionID);
// The system will be able to sleep again.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment