CoreFoundation main loop in plain C, macOS
10:59 28 Feb 2026

Please, pardon my possibly asking a thing too obvious or too absurd to be asked at all. I'd like to write a simplest sample C code for a command line program which runs a non-blocking loop and catches any keyboard input from user, eventually exiting the loop and program if a condition is met. I know how to do it in Cocoa, posix and traditional unix.

It's not a matter of why I would need it. I'm just looking forward to learn if this is possible in CF? - I surely must be missing something essential.

I understand I may have gotten it all wrong, but I found no documentation on whether this is possible or not. I understand I may be lurking in the dark corners of macOS programming, that nobody really needs. I've come this far. Thanks for having read the question.

//  mainloop.c
//  main loop CF demo
//
#import  
#include 
#include 

CFRunLoopObserverRef runloopObserver;

int main(int argc, const char * argv[]) {

    printf("\n-- CF main loop program --\n\n");
    
    runloopObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault,
                                 kCFRunLoopAllActivities,
                                 true,
                                 0,
                                 ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity)
                                      {
                                      printf("Activity : %lu\n", activity);
                                      // handler code ...
                                      if (activity == kCFRunLoopAfterWaiting){
                                         printf("Activity1: %lu\n", activity);
                                         //do something to exit main loop and program.
                                         CFRunLoopStop(CFRunLoopGetMain());
                                         printf("Exit\n");
                                         }
                                       }
                                       );
    CFRunLoopAddObserver(CFRunLoopGetMain(), runloopObserver, kCFRunLoopDefaultMode);
    CFRunLoopRun();
    return 0;
}
c macos command-line-interface core-foundation