Run and make daemon

Assume you have a binary or jar in some directory and you want to run it as daemon (which will not be killed as long as the os is runing)

use systemd/systemctl on Linux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Unit]
Description=Tests systemd to daemonize a Go binary
Document=
Wants=network.target
After=network.target

[Service]
Type=simple
DynamicUser=yes
ExecStart= your command (./some/dir/binary -args) or (java -cp classes -args)
WorkingDirectory= your desired working directory
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

Store the above as /usr/lib/systemd/system/foo.service

Start the service with:

1
$ sudo systemctl start foo.service

And enable it during startup with:
1
$ sudo systemctl enable foo.service

You can check the status of the service with:
1
$ systemctl status foo.service

On mac system

use launchd/launchctl on MacOS

Launchd uses xml for configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.username.test</string>

<key>ProgramArguments</key>
<array>
<string>/path/to/script.sh</string>
</array>

<key>Nice</key>
<integer>1</integer>

<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>17</integer>
<key>Minute</key>
<integer>55</integer>
</dict>

<key>RunAtLoad</key>
<true/>

<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string><![CDATA[/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin]]></string>
</dict>
<!-- for the use of node and brew packages -->

<key>StandardErrorPath</key>
<string>/tmp/Test.err</string>

<key>StandardOutPath</key>
<string>/tmp/Test.out</string>
</dict>
</plist>

to run the daemon as root user
1
2
cp com.username.plist /Library/LaunchDaemon/
launchctl load com.username.plist

to run only when you login
1
2
cp com.username.plist ~/Library/LaunchAgents/
launchctl load com.username.plist