Creating a simple service in macOS
2021-08-04 19:51:47

PLIST files are formatted in XML and stand for property list files. They’re typically used by macOS applications for defining properties and configurations settings related with how the application itself will behave as a daemon/service.

See the following simple example for defining a service that will be greeting your everytime you turn on your mac:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.agent</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>-c</string>
<string>say hello $USER</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>

The file above will be launched by running launchctl which is the command line interface for interacting with launchd. For those who are not familiar with launchd, it’s the service management framework used by macOS, similar in some ways to Service Control Manager on Windows or systemd on many Linux distributions.

Copy the snipped above and paste its content in a new file placed in ~/Library/LaunchAgents/com.example.agent.plist

First of we will proceed validating the plist file by running:

plutil ~/Library/LaunchAgents/com.example.agent.plist

output:

/Users/<username>/Library/LaunchAgents/com.example.agent.plist: OK

Now turn on your audio and proceed for activating our agent that will be greeting your everytime your mac is turned on:

launchctl load -w ~/Library/LaunchAgents/com.example.agent.plist

Here there is! you should have listened Siry greeting you, easy right?

In order to verify that the agent is running just type:

launchctl list com.example.agent

output:

1
2
3
4
5
6
7
8
9
10
11
12
{
"LimitLoadToSessionType" = "Aqua";
"Label" = "com.example.agent";
"OnDemand" = true;
"LastExitStatus" = 0;
"Program" = "/bin/sh";
"ProgramArguments" = (
"/bin/sh";
"-c";
"say hello $USER";
);
};

As this is just a simple example about how services are managed in the macOS echosystem, anytime you want to turn off the agent just type:

launchctl unload -w ~/Library/LaunchAgents/com.example.agent.plist

Hope you find this brief introducction to how services/daemons are managed by macOS useful, if you want to know more visit:

Stay tuned!