【问题标题】:How to fork/background a subprocess without stalling the parent process如何在不停止父进程的情况下分叉/后台子进程
【发布时间】:2015-05-07 05:08:37
【问题描述】:

我在 Mac OS X Yosemite 上运行带有 zsh/oh-my-zsh 的 bash shell。

所以我的目标是创建一个函数来获取一些信息(如果存在)并返回该信息,然后生成一个子进程来生成该信息以供下次使用。原因是生成信息的这个函数很慢(有时 2-5 秒),我不希望父 shell 在创建时挂起。

我正在创建这个函数作为 zsh 主题的提示装饰器,所以每次重新生成提示时都挂这么长的时间会真的不好。这个解决方案(或任何替代的无挂起解决方案)几乎可以工作,或者该功能被废弃。

现在我正在使用以下代码:

decorations=""
getDecs () {
    echo $decorations
    ( buildDecorationList & )
}

buildDecorationList () {
    local RetStr=""
    RetStr+=$(getList1) # Returns a list of stuff
    local temp=$(getList2) # Returns a second list of stuff
    if [[ $RetStr != "" && $temp != "" ]]; then
        RetStr+=", "
    fi
    RetStr+=$temp
    echo $RetStr # Return both lists concatenated
}

它非常接近工作,并实现了我想要的大部分内容,因为它不会停止主进程并且它会正确生成所有信息。我只是无法将此函数的输出正确地引导回主 shell 中的 decorations 变量,以便在下一次函数调用时检索它。

我尝试了各种形式的重定向/变量赋值,但它们总是以 a) 无法返回主 shell 和/或无法访问或 b) 导致父函数在等待输出时挂起.

我还研究了协同进程,因为它们一开始听起来很有希望,但我不太确定它们与子shell 有何不同,而且它们似乎对这个特定用例有相同的限制。或者我没有正确使用它们。同理。

我也考虑过使用具有特定名称的外部文件,但如果用户决定打开多个会话,那将变得极其复杂...

【问题讨论】:

    标签: macos bash shell zsh


    【解决方案1】:

    您可以将结果放入 tmp 文件中(使用mktmp)。 您在 main 函数中创建 tmp 文件,将其引用存储在全局变量中。所以它可以从主函数和子函数访问,如果设置了变量,您可以将逻辑放在主函数中,而不是重新启动子进程。

    您最终可以使用一种.lockcomplete 文件来表示进程已完成

    decoration_file=""
    
    getDecs () {
        if [ -z "$decoration_file" ] ; 
        then 
            decoration_file=`mktemp -t decoration`
           ( buildDecorationList & )
        elif [ ! -f "$decoration_file.complete" ]
              # non terminated, do the logic you want
    
        else
             cat $decoration_file
        fi
    
    }
    
    buildDecorationList () {
        local RetStr=""
        RetStr+=$(getList1) # Returns a list of stuff
        local temp=$(getList2) # Returns a second list of stuff
        if [[ $RetStr != "" && $temp != "" ]]; then
            RetStr+=", "
        fi
        RetStr+=$temp
        echo $RetStr > $decoration_file  # Return both lists concatenated
        touch ${decoration_file}.complete
    }
    

    如果要进行多次计算,您可能会适应这种情况

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多