Mac Service Management-launchd

Source: Internet
Author: User

Background:

There are not many tools for Init on the Mac like Linux, as you can tell from the history of Init https://en.wikipedia.org/wiki/Init that Mac uses launchd as the INIT management tool, The corresponding command tool is LAUNCHCTL.

If you are creating a self-starting service under Linux, you can use Upstart, SYSTEMD, Sysvinit, the simplest and oldest of which should be sysvinit, after all, it is very convenient to support shell scripts. And under the Mac, and the practice of Linux is not the same, the use of launchd for management, its settings services using the Plist file to describe the service, and through the configuration and put in /System/Library/LaunchDaemons or/Library/LaunchDaemons,最后通过launchctl命令行使其生效,期间也可以直接通过launchctl来对服务进行操作,比如启动、停止等。

Detailed plist writing specification and introduction, reference: HTTPS://EN.WIKIPEDIA.ORG/WIKI/LAUNCHD

Here is a detailed explanation of Launchd:

What is Launchd?

Mac OS x starts with 10.4 and uses LAUNCHD to manage services and processes for the entire operating system. Traditional UNIX uses/etc/rc.* or other mechanisms to manage startup Services to start when booting, and now Mac OS X uses LAUNCHD to manage its startup service called launch Daemon and launch Agents. And as a service, it is background process, should not provide GUI, and should not jump to (console) Foreground. There are, of course, exceptions, such as programs that jump out of windows after listening to quick keys.

There are four types of background process LAUNCHD management:

    1. Launch Daemon: Load (load) at boot time.
    2. Launch Agent: Loaded when the user logs on.
    3. XPC Service: It seems to be 10.7.
    4. Login Items: Executed at user login. There are two ways to add a program to login item: A shared File list: The login item list that will appear in account preferences. Service Management Framework: This will not appear in the Login item list. )

(The following emphasis is placed on launch daemon/agent.) As for XPC and login item do not explain first. )

Launch Daemon & Launch Agent

Launch Daemon and Launch agents are different names of the same kind of things in various scopes. Launch Daemon is a service of system-wide (System level), called the Daemon,launch agent, which is a service of per-user (User level), called the agent, which is loaded (load) at boot time, The latter is loaded when the user logs on (only).

If you open activity Monitor and switch to hierarchy View, you will find that there is a launchd on the top level, with the same layer of only kernel_task, it has a lot of child processes under the user is root, There is also a launchd, starting the user is yourself, it is under the child processes the user is almost your own. When these processes are executed by launchd loading the Launchd property List file, the former is performed by Root called Launch Daemons, which is performed by the user called launch Agents.

The Launchd property list file is the *.plist file you will see in the Launchdaemon or launchagents directory (hereinafter referred to as the plist file). It is in XML format.

Launchd Service Process Lifecycle

Services managed by Launchd (Launch Daemon, Launch Agent) are executed (run) after the LAUNCHD load (load), but are not necessarily executed immediately after loading. The official Apple document explains what happens when the kernel is loaded, to illustrate the life cycle of Launch daemons, Launch agents, and its processes.

When booting, the OS Kernel is loaded, and the launchd is executed after the load is completed to load System-wide Services (daemons). This system-wide launchd will do these things at boot time:

    1. Load (load) stored in these directories plist: (/system/library/launchdaemons,/library/launchdaemons)
    2. Register the sockets (port) and file descriptors that are set in the Plist
    3. Execute (Run) KeepAlive = True daemons, of course Runatload = True will also start.

After run, Loginwindow appears, prompting the user to log in. If you have a setting for automatic login, you will skip this switch.

After the user logs in, the user will be executed launchd, responsible for handling the launch Agent, do things like load launch daemon above, the difference is that it from the following directory loading plist:

    • /system/library/launchagents
    • /library/launchagents
    • ~/library/launchagents

Any program executed by the user is also performed by Launchd, so Launchd is also the mother of all processes of the user.

Termination Event is triggered when the user is logged out, shut down, or rebooted. The process of accepting logout, shutdown, and reboot user instructions is Loginwindow. It will be confirmed to the user first, but the confirmation, will be sent to each of the user's launchd initiated by the processes termination Signal, if cocoa is sent out Cocoa API event, The rest is sent out sigterm to self-terminate, after 45 seconds, in addition to the cocoa application can throw an error to cancel the entire termination Process, the other is not finished will be killed.

This is why the Loginwindow process is always there, and it is responsible for clearing the processes that the user executes. When Per-user services are switched off, they go back to Loginwindow, or perform a shutdown and reboot process, and the latter two follow the same process to turn off all system-wide Services.

Launchd-compatible Daemon Programming Guide

The following is a reference to what should be noted in this document in conjunction with LAUNCHD Development Daemon, referring to the man 5 launchd.plist for key plist. The following daemon refers to the process that launch daemon to run, so the launch agent applies as well.

Listen to SIGTERM

As mentioned above, because Loginwindow this process in want to turn off your daemon will send Sigterm, want you self-end, wait too long not turn off will Sigkill. If your program needs to do something before it ends, be sure to listen to sigterm this signal.

On-demand Daemon

Launch Daemon/agent does not allow a process to execute by default, and when its setting is not keepalive = True, it will be based on the CPU usage and requests of the process being executed, such as TCP/IP Service) to decide whether or not to send out sigterm call him to commit suicide.

When the service needs to be used, and the corresponding program does not run into a process, the service is automatically run up. For example, if a TCP/IP service listens to a port, when the port has a packet in it, LAUNCHD will start the corresponding service, which is called On-demand.

Of course, there are non-on-demand daemon, in fact, keep-alive Daemon, which is also the traditional sense of daemon, for example, has been hiding in the corner silently execution, until someone find him, he jumped back and forth, and then continue to hide in the corner. As long as the KeepAlive key is set to True, it will execute (run) when the plist is launchd loaded (load). If that process dies, launchd will know and open it up soon. So if you try to go to the activity monitor and cut off the daemon, it will immediately revive.

No Fork or exec

The traditional system programming will teach you to do daemon with the POSIX API of exec, fork, and so on, but with Launchd, the daemon life cycle is controlled by launchd, unless kepp-alive is enforced, Otherwise to be born to die is launchd decision, not to mention Keep-alive also consider daemon process after the end of automatic re-execution, so in conjunction with launchd write daemon, Apple recommends you do not use the traditional fork and exec*. Of course, the programarguments in the plist file is the parameter of the Exec* series subroutine.

When a process runs and dies within 10 seconds, LAUNCHD will be judged as crash and then tried to re-execute. If you use the traditional fork-exec style, you may create an infinite loop.

No Setuid/setgid/chroot/chdir etc

For security reasons, Apple strongly recommends that you do not call Setupd, Setgid, chroot, chdir, etc. system subroutines, but through the plist file set value to let Launchd help you complete, refer to username, The keys of GroupName, RootDirectory and WorkingDirectory.

No pipe redirection Hell for FD 0, 1 or 2

In writing log or output information can be set Standardoutpath, Standarderrorpath, just output to stdout or stderr is good. Standardinpath also allows you to specify the contents of the path from stdin as soon as your process executes. In other words, LAUNCHD helps you pass FD = 0, 1, 2 things all over again.

Other applications

Scheduled Tasks

Launch Daemon/agent's settings can specify the service's execution period and execution time, which means it can replace traditional at, periodic, and Cron. Please refer to Startinterval and startcalendarinterval for these setpoint keys.

With launchonlyonce words can be simulated at, but if you want to use LAUNCHD only temporarily do one thing, it is not as direct at convenience.

Monitor file or directory movement

Launch Daemon/agent can monitor the action of a path and set it to the Watchpaths key. The path mentioned here can be either directory or a specific file, as long as the path has a different action, it will execute your job.

can also be used to clear the queue, as long as there is something in the directory, will execute the job until empty, can be used to do mail server or notification. Set this key in Queuedirectories.

Reference:

Https://en.wikipedia.org/wiki/Init

Https://en.wikipedia.org/wiki/Launchd

Https://stackoverflow.com/questions/15735320/osx-s-etc-init-d-equivalent

Https://nathangrigg.com/2012/07/schedule-jobs-using-launchd#launchctl

Https://blog.yorkxin.org/2011/08/04/osx-launch-daemon-agent (the above content is transferred from this blog, because of traditional translation into simplified, some places may have semantic problems)

Https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html

Https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/launchctl.1.html

Https://developer.apple.com/library/content/technotes/tn2083/_index.html

Mac Service Management-launchd (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.