在bash简单的背景处理问题 [英] Simple background process question in bash

查看:195
本文介绍了在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 code,然后你可以捕捉某种方式和评估。

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确保最简单的方法也只是让你的函数输出code到一个临时文件,然后在源到底该文件。所以,你会改变职能,如:

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天全站免登陆