views:

368

answers:

1

Hi I am trying to develop a daemon using objective-C/xcode.

I am new to mac world and can I get an idea of what project template to choose in xcode and how to do it.

Can I get a simple and basic daemon sample source code ?

+1  A: 

The "Command Line Tool" project is sufficient to start writing a daemon. There are no special build requirements as such, it just depends on what you want the daemon to do.

The way to write a Mac OS X daemon is very much like the way you would approach it on a regular Unix system. Accordingly, there are a few things to keep in mind:

  • non-interactive: you don't get direct input from the user, but you also have to use something like syslogd for output, as the process is not attached to a terminal
  • environment: don't assume it has a particular current directory, path, default permissions, or any other environmental settings - explicitly set these up
  • security: ensure the daemon has the barest minimum privileges required to perform its function, and no more (this is a huge topic in itself)
  • signals: you will need to trap and respond to certain signals, as these are typically used for process control (eg. SIGHUP forces the daemon to reload its config file)

There are some good writeup on Unix daemons if you go looking. The Stephens book on Unix is always good, too.

There is some Mac specific information on daemons to consider, mainly regarding integrating with launchd.

A typical daemon will do something like the following:

  • double-fork, to detach from the parent process
  • set up process group and effective UID
  • install signal handlers
  • set file permissions umask
  • change directory to a work directory
  • read configuration file
  • open sockets, etc
  • go into an infinite loop to service requests

There is a simple daemon example in the Wikipedia article too.

gavinb
To clarify, this will be a `LaunchDaemon`, and not a `LaunchAgent`. `LaunchDaemon`s run as root (which is needed to run before login), and `LaunchAgent`s run as the user.
Dave DeLong