Bash スクリプトが無効な PID を返します。

Bash スクリプトが無効な PID を返します。

bashスクリプトを実行すると、誤ったPIDが得られます。プロセスを終了するにはPIDが必要です。以下は、問題の影響を受ける単純化されたスクリプトです。

echo 'PASSWORD' | sudo -S ping -f '10.0.1.1' & 
PING_PID=$BASHPID; 
echo $PING_PID;

出力例

[1] 14336

PC:~ Account$ PING 10.0.1.1 (10.0.1.1): 56 data bytes
.
.PC:~ Account$..Request timeout for icmp_seq 18851
...

しかし、Activity Monitor(Mac)を見ると、pingプロセスにPIDがあることがわかりますが、14337なぜ変数にthenが含まれているのです14336か?

ベストアンサー1

$ BASHPIDは現在のプロセスのPIDですbash。具体的には、特殊パラメータとジョブ制御を参照してください$!。また、man bash(flood)を使用している場合にのみping必要です。代わりに何を実行しているのかがわかるので、PIDが返されるので、使用すると状況が複雑になる可能性があります。sudo-fsudobashsudoping$!sudo

$ ping -c 5 www.example.com & echo "The PID of ping is $!" ; sleep 6
[1] 4022
The PID of ping is 4022
PING www.example.com (192.168.218.77) 56(84) bytes of data.
64 bytes from 192.168.218.77: icmp_seq=1 ttl=64 time=0.260 ms
64 bytes from 192.168.218.77: icmp_seq=2 ttl=64 time=0.329 ms
64 bytes from 192.168.218.77: icmp_seq=3 ttl=64 time=0.382 ms
64 bytes from 192.168.218.77: icmp_seq=4 ttl=64 time=0.418 ms
64 bytes from 192.168.218.77: icmp_seq=5 ttl=64 time=0.434 ms

--- www.example.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4000ms
rtt min/avg/max/mdev = 0.260/0.364/0.434/0.066 ms
[1]+  Done                    ping -c 5 www.example.com
$

おすすめ記事