How to lock screen from command line on a Mac

Posted by yingbo on Mon 22 September 2014

Interesting enough, there is no easier way than do a little "programming". I found the following solution on

Creating "main.m" by any text editor:

#import <objc/runtime.h>
#import <Foundation/Foundation.h>

int main () {
    NSBundle *bundle = [NSBundle bundleWithPath:@"/Applications/Utilities/Keychain"];

    Class principalClass = [bundle principalClass];

    id instance = [[principalClass alloc] init];

    [instance _lockScreenMenuHit:NULL];

    return 0;

Then compile it with clang (from Xcode):

clang -framework Foundation main.m -o lock

Then run the "lock" will lock your screen immediately.