LoginSignup
101
105

More than 5 years have passed since last update.

Macのlaunchctlでサービスの自動起動をさせたくない時のためのメモ

Last updated at Posted at 2014-11-13

homebrewでMavericksにインストールしたdnsmasqがサービス管理にlaunchctlを利用していた。

> brew install dnsmasq
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/dnsmasq-2.72.mavericks.bottle.tar.gz
######################################################################## 100.0%
==> Pouring dnsmasq-2.72.mavericks.bottle.tar.gz
==> Caveats
To configure dnsmasq, copy the example configuration to /usr/local/etc/dnsmasq.conf
and edit to taste.
  cp /usr/local/opt/dnsmasq/dnsmasq.conf.example /usr/local/etc/dnsmasq.conf
To have launchd start dnsmasq at startup:
    sudo cp -fv /usr/local/opt/dnsmasq/*.plist /Library/LaunchDaemons
    sudo chown root /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
Then to load dnsmasq now:
    sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
WARNING: launchctl will fail when run under tmux.
==> Summary
?  /usr/local/Cellar/dnsmasq/2.72: 7 files, 496K

launchctlを用いたサービス管理の基本的な操作をメモする

サービスのplistファイル

dnsmasqの場合はこのようなplistファイルが添付されているので、サービスに登録するにはこれをLaunchDaemonディレクトリ(いくつかある)に配置する必要がある。

<?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>homebrew.mxcl.dnsmasq</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/opt/dnsmasq/sbin/dnsmasq</string>
      <string>--keep-in-foreground</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
  </dict>
</plist>

サービスのロード

sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist

サービス情報を記録したサービス名のplistファイルをサービスとしてロードする。plistファイルはフルパス。
サービスを起動するためには後述するlaunchctl startが必要だが、plistに自動起動が設定されていた場合は即座にサービスが起動する。

サービスのアンロード

sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist

サービスをアンロードする。起動していたサービスは終了する。

サービスの起動

sudo launchctl start homebrew.mxcl.dnsmasq

ロードしたサービスを起動する。

サービスの終了

sudo launchctl stop homebrew.mxcl.dnsmasq

起動したサービスを終了する。ただし、plist内で

    <key>KeepAlive</key>
    <true/>

と記述されていたら、終了してもすぐに自動的に再起動される。

サービスの自動起動

サービスのplist内で

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

と記述されていたら、サービスのロード時(OS起動時を含む)に自動的にサービスが起動される。

まとめ

homebrewでインストールしたサービスが未来永劫勝手に起動されてしまうのが嫌だったら、RunAtLoadをfalseに設定すれば良い。または、plistのProgramArgument要素を覗けば叩いているコマンドラインが分かるので、それを見て勝手に叩けばよい。その場合、サービスを起動するにはlaunchctl loadしてからlaunchctl startする必要がある。

101
105
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
101
105