Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

multithreading - Simple background process question in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you run something in the background, it runs as a separate child process, with its own environment.

It cannot affect the environment of the current process (the parent process of those subshells).

So it's not so much that the variables aren't available outside of the function as they're not available outside of the process. The function is irrelevant since, if you run them in the foreground (without the &), the variables are set just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...