Reputation: 95
I am new to Mac OSX and i am trying to develop a daemon (i am familiar with windows services, and trying to achieve about the same things).
What i did so far:
Managed to write a plist file in LaunchDaemons (i found out that those daemons run under system account, not user, just like a windows service with local system permissions).
I managed to make it run on startup, and run my simple hello world application that just writes something to a file every 10 seconds.
The problem is, when i unload the daemon with launchd, it just kills my process. Is it any way to have the daemon either run something else on unload, or communicate to my process that it is shutting down, so i can perform an unload action in my code?
Thank you
Upvotes: 2
Views: 783
Reputation: 27611
The lifecycle of a daemon is documented by Apple and they describe how to handle Terminating Processes
If you're using Objective-c or Swift, you should be able to implement the applicationshouldterminate delegate method.
If you're not using Cocoa:
Non-Cocoa applications receive a “Quit Application” Apple event (kAEQuitApplication), as a courtesy, to give them a chance to shut down gracefully
Finally, since you're running a daemon (background process)
For background processes, the procedure is a little different. The loginwindow program notifies the process that it is about to be terminated by sending it a Quit Application Apple event (kAEQuitApplication). Unlike foreground processes, however, loginwindow does not wait for a reply. It proceeds to terminate any open background processes by sending a SIGKILL signal, regardless of any returned errors.
If the system is being shut down or restarted, it sends a SIGTERM signal to all daemons, followed a few seconds later by SIGKILL signal.
There's a discussion on handling SIGTERM here.
Upvotes: 3