bash中的简单后台进程问题 [英] Simple background process question in bash

查看:19
本文介绍了bash中的简单后台进程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BASH,我正在调用几个更新几个变量的函数.这些功能需要很长时间才能完成,所以我想在后台运行所有功能,以便它们可以同时运行.这是我要问的基本示例.

I am using BASH and I am calling a couple of functions which update a couple of variables. These functions take too long to complete so I was thinking running all of the functions in the background so that they can be running simultaneously. This is a basic example of what i am asking.

#/bin/bash

func1()
{
    var1="one"

}

func2()
{
    var2="two"

}

func3()
{
    var3="three"

}

echo "Right now this is what i am doing"
func1 &
func2 &
func3 &
wait
echo "The variables are $var1 $var2 $var3"
echo "But the variables are empty. 
echo "Hence, I am assuming that they are not accessible outside of the function"

我觉得我错过了一些非常愚蠢的东西.当然,如果我不在后台运行这些函数,它们会显示正确的变量.提前致谢.

I feel like I am missing something very silly. Of course if I don't run the functions in the background, they show the correct variables. Thank you in advance.

推荐答案

如果你真的需要这样做,一个技巧就是让你的函数打印出 bash 代码,然后你可以以某种方式捕获并评估.

If you really need to do it a hack would be to have your functions print out bash code, which you could then capture somehow and evaluate.

可以肯定,最简单的方法就是让您的函数将代码输出到临时文件,然后在最后获取该文件.因此,您可以将函数更改为:

Pretty sure the easiest way would just be to have your functions output the code to a temp file and then source that file at the end. So you would change the functions to be like:

func1(){
    echo "var1=one"
}

然后在最后做一些事情:

then at the end do something like:

TEMPFILE=`mktemp`
func1 >> $TEMPFILE &
func2 >> $TEMPFILE &
func3 >> $TEMPFILE &
wait
source $TEMPFILE
rm $TEMPFILE
echo "$var1 $var2 $var3"

如果函数本身正在打印输出,那么您可能需要执行一些操作,例如导出保存临时文件名称的变量,然后在函数中进行重定向,即:

If the functions themselves are printing output then you might have to do something like export the variable holding the name of the temp file and then have the redirect in the function, viz:

export TEMPFILE=`mktemp`
func1(){
    echo "var1=one" >> $TEMPFILE
}

不要忘记删除临时文件...

don't forget to delete temp files...

注意:可能有更好的方法.

NOTE: There is probably a much better way.

这篇关于bash中的简单后台进程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆