首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何退出子Subshell

如何退出子Subshell
EN

Stack Overflow用户
提问于 2016-12-28 21:39:16
回答 1查看 4.9K关注 0票数 0

基本上,我试图退出一个包含循环的子subshell。这是代码:`

代码语言:javascript
复制
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

这不管用。从来没说过已经完成了。当我按“停止”时,它只会关闭对话框,但会一直写到文件中。

编辑:我需要能够将一个变量从子shell传递给父shell。然而,我需要继续写到文件,并保持Zenity对话框即将出现。我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-28 21:49:25

当您生成子shell时,它会创建当前shell的子进程。这意味着,如果在一个shell中编辑一个变量,它将不会反映在另一个shell中,因为它们是不同的进程。我建议您将子send发送到后台,并使用$!获取它的PID,然后在准备就绪时使用该PID杀死子send。看起来是这样的:

代码语言:javascript
复制
(                               # 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41370092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档