xcrun simctl terminateは、実行中のアプリをbundle identifierで指定して終了するサブコマンドである。

参考: xcrun simctl launchでiOSシミュレータのアプリを環境変数・引数付きで起動する

基本的な使い方

terminate <device> <bundle identifier>の形式で実行する。

$ xcrun simctl launch "TIL Terminate iPhone" com.apple.mobilesafari
com.apple.mobilesafari: 12599

$ xcrun simctl terminate "TIL Terminate iPhone" com.apple.mobilesafari
$ ps aux | grep MobileSafari.app/MobileSafari
(該当プロセスなし)

対象デバイスは起動中(Booted)である必要がある

installappinfoなどと同様、対象デバイスが起動中でないとUnable to lookup in current state: Shutdown(code=405)でエラーになる。

終了対象が見つからない場合はエラーになる

参考: xcrun simctl install/uninstallでiOSシミュレータにアプリをインストール・削除する

uninstallは対象が存在しなくてもエラーにならない冪等な動作だったが、terminateは実行中のプロセスが見つからないと明確なエラーになる。

$ xcrun simctl terminate "TIL Terminate iPhone" com.apple.mobilesafari
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=3):
Simulator device failed to terminate com.apple.mobilesafari.
found nothing to terminate

このエラーは、アプリがインストール済みだが起動していない場合と、bundle identifier自体が存在しない場合の両方で同じfound nothing to terminateになり、区別できない。

terminateしてからlaunchし直すとプロセスが入れ替わる

参考: xcrun simctl launchでiOSシミュレータのアプリを環境変数・引数付きで起動する

起動中のアプリへの再launchはPIDが変わらないが、terminateを挟んでからlaunchし直すと新しいプロセスとして起動しPIDが変わる。

$ xcrun simctl launch "TIL Terminate iPhone" com.apple.mobilesafari
com.apple.mobilesafari: 13397

$ xcrun simctl terminate "TIL Terminate iPhone" com.apple.mobilesafari
$ xcrun simctl launch "TIL Terminate iPhone" com.apple.mobilesafari
com.apple.mobilesafari: 13457

launch--terminate-running-processオプションは、このterminatelaunchの2手順を1回のコマンドにまとめたものである。

アプリ本体のプロセスは終了するが、関連プロセスが残ることがある

Safariのようにアプリ拡張(App Extension)を持つアプリでは、terminateはアプリ本体のプロセスだけを終了し、そこから起動された拡張のプロセスは終了しない場合がある。

$ xcrun simctl launch "TIL Terminate iPhone" com.apple.mobilesafari
$ ps aux | grep SafariWidgetExtension.appex
sue  12698 ... .../MobileSafari.app/PlugIns/SafariWidgetExtension.appex/SafariWidgetExtension ...

$ xcrun simctl terminate "TIL Terminate iPhone" com.apple.mobilesafari
$ ps aux | grep MobileSafari.app/MobileSafari
(該当プロセスなし、アプリ本体は終了している)
$ ps aux | grep SafariWidgetExtension.appex
sue  12698 ... .../MobileSafari.app/PlugIns/SafariWidgetExtension.appex/SafariWidgetExtension ...
(拡張プロセスは残ったまま)

拡張のプロセスが起動するまでには数秒〜十数秒のタイムラグがあり、launch直後のpsではまだ現れない。 確認する際はlaunch後に少し待ってからpsで見る必要がある。

アプリに紐づくプロセスをすべて確実に終了させたい場合は、terminateだけに頼らずデバイス自体をshutdownする必要がある。