2016-12-28 7 views
0

基本的には、ループを含むサブシェルを終了しようとしています。コードは次のとおりです。 サブシェルを終了する方法

stop=0 
( # subshell start 
    while true   # Loop start 
    do 
     sleep 1   # Wait a second 
     echo 1 >> /tmp/output   # Add a line to a test file 

     if [ $stop = 1 ]; then exit; fi   # This should exit the subshell if $stop is 1 
    done # Loop done 

) |   # Do I need this pipe? 

    while true 
    do 
     zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew  # This opens Zenity and shows the file. It returns 0 when I click stop. 

     if [ "$?" = 0 ]  # If Zenity returns 0, then 
     then 
     let stop=1  # This should close the subshell, and 
     break  # This should close this loop 
     fi 
    done  # This loop end 
    echo Done 

これは機能しません。 Doneとは決して言わない。停止ボタンを押すと、ダイアログが閉じられますが、ファイルには書き込みが続けられます。

編集:サブシェルから親シェルに変数を渡すことができる必要があります。しかし、私はファイルへの書き込みを続け、Zenityダイアログを立ち上げておく必要があります。どうすればいい?

+0

私は分かりません。サブシェルを終了する特別な方法はありますか? – Feldspar15523

答えて

2

サブシェルを起動すると、現在のシェルのサブプロセスが作成されます。これは、あるシェル内の変数を編集すると、異なるプロセスであるため、変数が他のシェルに反映されないことを意味します。サブシェルをバックグラウンドに送り、$!を使用してPIDを取得し、そのPIDを使用して準備ができたらサブシェルを終了させることをお勧めします。これは次のようになります。

(        # subshell start 
    while true     # Loop start 
    do 
     sleep 1     # Wait a second 
     echo 1 >> /tmp/output # Add a line to a test file 
    done      # Loop done 

) &        # Send the subshell to the background 

SUBSHELL_PID=$!     # Get the PID of the backgrounded subshell 

while true 
do 
    zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew  # This opens Zenity and shows the file. It returns 0 when I click stop. 

    if [ "$?" = 0 ]    # If Zenity returns 0, then 
    then 
    kill $SUBSHELL_PID   # This will kill the subshell 
    break      # This should close this loop 
    fi 
done       # This loop end 

echo Done 
+0

括弧付きの明示的なサブシェルは役に立たない(おそらく欲しくない)。 –

+0

これは、かっこの有無にかかわらず動作します。サブシェルをバックグラウンドまたはループに送信するだけです。私は個人的にサブシェルが好きです。バックグラウンドに送られているものを明確にするためです。「while ......... done&」とは異なり、 'done'のように見えます。それでも動作します)。括弧を省略する魅力的な理由はありますか? –

+0

サブシェル内の変数を変更すると、それがメインで変更されますか?そうでない場合は、どうやって2つの間で価値を出すのですか? – Feldspar15523

関連する問題