force stop main RunLoop in SIGTERM handler

Hello, I am developing launch agent which sets signal handler for SIGTERM. I am calling CFRunLoopRun() in main thread. Is it safe to call CFRunLoopStop(CFRunLoopGetMain()) in SIGTERM signal handler?

Thank you for your help!

Answered by DTS Engineer in 779980022

How did you install the handler? Via signal or sigaction? Or via a Dispatch source?

If the Dispatch case, you could schedule the source on the main queue and then reasonably call CFRunLoopStop from its event handler.

In the signal or sigaction case, you can’t do any of that. Such handlers are limited to async signal safe functions, as defined in the sigaction man page. That severely constrains what they can do. For example, malloc isn’t async signal safe, and neither is the Swift or Objective-C runtimes O-:

Finally, my general advice on this is that you not try to terminate your main run loop like this. Rather, just call exit from your Dispatch source event handler. My experience is that folks exit their run loop because they want to run termination code, and you can just do that before you call exit. If you’re using implicit termination code, like C++ static destructors, it’s better to factor out the code that really needs to run and run it explicitly.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

How did you install the handler? Via signal or sigaction? Or via a Dispatch source?

If the Dispatch case, you could schedule the source on the main queue and then reasonably call CFRunLoopStop from its event handler.

In the signal or sigaction case, you can’t do any of that. Such handlers are limited to async signal safe functions, as defined in the sigaction man page. That severely constrains what they can do. For example, malloc isn’t async signal safe, and neither is the Swift or Objective-C runtimes O-:

Finally, my general advice on this is that you not try to terminate your main run loop like this. Rather, just call exit from your Dispatch source event handler. My experience is that folks exit their run loop because they want to run termination code, and you can just do that before you call exit. If you’re using implicit termination code, like C++ static destructors, it’s better to factor out the code that really needs to run and run it explicitly.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

thank you a lot!

force stop main RunLoop in SIGTERM handler
 
 
Q