我在上运行一个带有zsh/噢-my的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
}它是如此接近工作,并实现了我想要的大部分,因为它没有拖延的主要进程,它正确地生成所有的信息。我只是很难将这个函数的输出正确地定向回主外壳中的decorations变量,在下一个函数调用中可以在那里检索它。
我尝试过各种形式的重定向/变量赋值,但它们总是以以下两种形式结束:( a)不返回主shell和/或无法访问或( b)导致父函数在等待输出时挂起。
我还研究了协同过程,因为它们一开始听起来很有希望,但我不太确定它们与子seem有何不同,它们似乎对这个特定的用例具有相同的限制。否则我就没好好利用它们。Idk。
我还考虑使用具有特定名称的外部文件,但如果用户决定打开多个会话,这将变得极其复杂.
发布于 2015-03-10 19:53:12
您可以做的是将结果放入一个tmp文件(使用mktmp)。在主函数中创建tmp文件,将其引用存储在全局变量中。因此,它可以从主函数和子函数进行访问,如果设置了变量,则可以将逻辑放在主函数中,以避免重新启动子进程。
您最终可以使用某种.lock或complete文件来表示已完成的过程。
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
}如果要进行多次计算,您可能会调整这一点。
https://stackoverflow.com/questions/28884492
复制相似问题