How to start/stop/restart launchd services from the command line?

How do I restart, say for example my httpd or afpd, running any Mac OS X >= 10.5 (Leopard-), without having to use the GUI and go to System Preferences -> Sharing and unchecking/checking "Web Sharing"?

I'm looking for the canonical equivalent to Debian's invoke-rc.d apache2 restart.

EDIT: The question is about launchd controlled services in general, not specifically Apache (-which was simply an example).


Solution 1:

launchctl(8) is your friend. Just keep in mind that some of the services (sshd for example) are disabled in the configuration file so you will need to use the -w switch when loading them. Here is a sshd example:

$ sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist 

You can stop the service using the unload subcommand.

$ sudo launchctl unload  /System/Library/LaunchDaemons/ssh.plist 

To list the services, as you might have already guessed use the 'list' subcommand ;)

Solution 2:

To restart a service, you can use the launchctl kickstart command, together with the -k option. For example, to restart apache, you can use

sudo launchctl kickstart -k system/org.apache.httpd

This information is from the launchctl manual page:

 kickstart [-kp] service-target
          Instructs launchd to run the specified service immediately, regardless of its
          configured launch conditions.

          -k       If the service is already running, kill the running instance before
                   restarting the service.
          [...]