けけずんセルフハッキング

エンジニアっぽい雰囲気を醸しだしているかのようなブログです!

/bin/launchctl で色々と自動で起動する設定する

はじめに

よく分からんコマンド調べてみようシリーズ。

kkznch.hatenablog.com

今回は /bin/launchctl について。

/bin/launchctl

名前から推測するに CentOS でいう systemctl みたいな、 OS 起動時に自動でサービスの起動を設定する奴かね。 ということで man launchctl したときの DESCRIPTION の内容はこちら。

launchctl interfaces with launchd to manage and inspect daemons, agents and XPC services.

launchctl はデーモンやエージェント、XPC サービスの管理や検査をする launchd のインターフェース。よく分からない。

念の為 launchd についても man launchd してみた。

launchd manages processes, both for the system as a whole and for individual users.

launchd はシステム全体と個別のユーザのプロセスを管理するらしい。 なるほど、launchctl は launchd をどうこうするためのコマンドということでしょうか、そういうことにしておきましょう。

/bin/launchctl 実行してみる

説明だけだとよく分からんので動かそう。

plist ファイルを書く

何を実行するのか、どの間隔で実行するのか、などといった様々なオプションを plist 形式のファイルに書く。 今回は 10 秒間隔で echo するだけの test.plist というファイルを作成してみた。

<?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>test</string>
  <key>ProgramArguments</key>
  <array>
     <string>echo</string>
     <string>Hello,World!</string>
  </array>
  <key>StandardOutPath</key>
  <string>/path/to/output.log</string>
  <key>StartInterval</key>
  <integer>10</integer>
 </dict>
</plist>

ロードと起動

作成後は以下のコマンドで、フルパスで test.plist を指定してロードする。

$ launchctl load /path/to/test.plist

この時点ではまだ起動はしていない。 ロードした時点で起動するオプションもあるが、今回はないので手動で起動する。 起動時には test.plist の Label キーで指定した値(今回は test )を引数に渡す。

$ launchctl start test

これで完了。 このあと少し時間をおくと以下のように /path/to/output.logHello, World! が出力されているはず。

$ cat /path/to/output.log
Hello,World!
Hello,World!
Hello,World!

停止とアンロード

止める際は以下のコマンドで止めて、 unload してあげる。

$ launchctl stop test
$ launchctl unload /path/to/test.plist

以上。

おわりに

これは今後自分で plist を書いて何かを動かすということはあるのだろうか。 Linux とかだとなんとなく使い道は分かるが、mac だと何をするねん。

plist の書き方だったり細かいオプションは参考リンク先を見てね。

参考リンク

qiita.com www.minimalab.com