如何退出子壳



基本上,我正在尝试退出包含循环的子壳。这是代码:

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

这不起作用。它从未说过。当我按停止时,只需关闭对话框,但一直写入文件。

编辑:我需要能够将变量从子壳传递给父壳。但是,我需要继续写入文件,并保持" Zenity对话"。我该怎么做?

产生子壳时,它会创建当前外壳的子过程。这意味着,如果您在一个外壳中编辑一个变量,则不会反映在另一个外壳中,因为它们是不同的过程。我建议您将子壳发送到背景,并使用$!获取其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

相关内容

  • 没有找到相关文章

最新更新