LoginSignup
52

More than 5 years have passed since last update.

[Linux][shell] PIDを取得する方法まとめ

Last updated at Posted at 2015-11-30

shellの $! を使用して直前のPIDを取得する

shellの $!直前の実行プロセス 最後に実行したバックグラウンドプロセスのPIDを取得できる。
(少なくともbashでは使える) => POSIXで定義されているので基本使用できるとのこと

#!/bin/bash
hoge_detach_process &
pid=$!

ps コマンドから絞り込む

目で確認するだけか、同名のプロセスがない場合のみ可能。(直前であればPIDの番号の大きい方を使えば良いとは思われる)

# ps の C オプションで指定する
$ ps --no-heading -C <prog_name> -o pid

# grep で絞り込む
$ hoge_detach_process &
$ ps -e -o pid,cmd | grep hoge_detach_process | grep -v grep | awk '{ print $1 }'

# 正規表現を使用する
$ ps -e -o pid,cmd | grep -E "^.*hoge_detach_process$" | awk '{print $1}'
$ ps -e -o pid,cmd | awk '/^.*hoge_detach_process$/ {print $1}'

pidof コマンドを使用する

pidof program_name でPIDを取得できる。
組み込みLinux環境ではおそらく入ってないため使えない。

$ hoge_detach_process &
$ pidof hoge_detach_process

参考: Linuxコマンド集 - 【 pidof 】 プロセスのpidを調べる:ITpro

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
52