/dev/null

脳みそのL1キャッシュ

macOS の launchd を使ってサービスを自動起動する

はじめに

Linux には systemd という起動処理やシステム管理を行うプログラムがあります。systemd は /etc/systemd/system 以下に xxxx.service を作り systemctl enable xxxx と実行すれば、起動時処理を追加できます。

これを macOS でもやりたいわけですが、これは launchd を使えば実現できます。

plist ファイル

launchd を使って起動時になにかのプログラムを動作させるためには plist ファイルを作る必要があります。/Library/LaunchDaemons 以下に plist ファイルを作り launchctl コマンドでロードしてやれば、plist ファイルの内容に従ってプログラムが起動します。

$ sudo launchctl load /Library/LaunchDaemons/com.consul.plist

ちなみに停止するには unload してやればいいです

$ sudo launchctl unload /Library/LaunchDaemons/com.consul.plist

参考までに、以下は僕が登録している plist ファイルの一例です。

<?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.consul</string>
    <key>ProgramArguments</key>
    <array>
      <string>/Users/USER_NAME/Root/local/bin/consul</string>
      <string>agent</string>
      <string>-config-dir=/Users/USER_NAME/Root/etc/consul.d</string>
      <string>-node=macOS</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>NetworkState</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/consul-stdout.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/consul-stderr.log</string>
    <key>UserName</key>
    <string>USER_NAME</string>
  </dict>
</plist>

ポイントとしては

  • RunAtLoad で起動時に実行されるようにする
  • KeepAlive で自動で再起動を試みるようにする
  • NetworkState でネットワークデバイスが有効になり、IP アドレスが割り当てられているときに限りプログラムを動作させるようにする
  • StandardOutPath, StandardErrorPath で標準出力、エラー出力をファイルに残すようにする

ってところくらいですかねー。以上!

参考

qiita.com

medium.com