パイプラインコマンドを終了するには?

パイプラインコマンドを終了するには?

次の簡単なスクリプトがあるとしますaction.sh

#!/bin/bash
echo -n 'a' | nc a.b.c.d p

action.shaここに住所を割り当てるキャラクターを配置してくださいa.b.c.d

しかしnc、時には中断して終了したい場合もあります。

$ ./action.sh
^C

これはうまく機能し、ゾンビは残りません。

バックグラウンドに置いて終了しようとするとncアクティブなままであるため、手動でクリーンアップする必要があります。

& ./action.sh &
[1] 28747
& kill -15 28747 //here nc is still running! I have to find its PID and terminate it

終了信号を受信したときに終了を要求する方法もありますかaction.shnc

ベストアンサー1

#!/bin/bash

trap ctrl_c INT

function ctrl_c() {
    # redirect to stderr to avoid showing errors in case nc isn't found
    kill -9 $(pgrep nc) > /dev/null 2>&1
}

echo -n 'a' | nc a.b.c.d p

おすすめ記事