Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash脚本中避免竞争条件?_Bash_Race Condition - Fatal编程技术网

如何在bash脚本中避免竞争条件?

如何在bash脚本中避免竞争条件?,bash,race-condition,Bash,Race Condition,如何避免count=`expr$count+1`和n=`tail-1的竞争条件,这样当我同时运行两个脚本时,它只会变为100,而不是200。我已经在多个网站上进行了研究,但是如果没有强大的功能,没有简洁的答案。您已经安全地避免了使用锁文件的实际竞争情况。您描述的问题可以通过两种方式避免 1将锁文件移到主循环之外,使程序的两个实例不能同时运行其主循环。如果一个正在运行,另一个将不得不等待,直到它完成,然后开始替换输出文件 #!/bin/bash if [ ! -f numbers ]; then

如何避免count=`expr$count+1`和n=`tail-1的竞争条件,这样当我同时运行两个脚本时,它只会变为100,而不是200。我已经在多个网站上进行了研究,但是如果没有强大的功能,没有简洁的答案。

您已经安全地避免了使用锁文件的实际竞争情况。您描述的问题可以通过两种方式避免

1将锁文件移到主循环之外,使程序的两个实例不能同时运行其主循环。如果一个正在运行,另一个将不得不等待,直到它完成,然后开始替换输出文件

#!/bin/bash
if [ ! -f numbers ]; then echo 0 > numbers; fi
count=0
touch numbers
echo $count > numbers
while [[ $count != 100 ]]; do
  if ln numbers numbers.lock
  then
    count=`expr $count + 1`
    n=`tail -1 numbers`
    expr $n + 1 >> numbers
    rm numbers.lock
  fi
done
2通过检查文件的内容,使两个实例相互配合。换句话说,当数字达到100时,强制它们停止循环,而不管有多少其他进程正在写入此文件。我想当有100多个实例在运行时,会出现一个不确定的情况

#!/bin/bash
while true; do
    if ! ln numbers numbers.lock
    then
       sleep 1
    else
        if [ ! -f numbers ]; then echo 0 > numbers; fi
        count=0
        touch numbers
        #echo $count > numbers   # needless, isn't it?
        while [[ $count != 100 ]]; do
            count=`expr $count + 1`
            n=`tail -1 numbers`
            expr $n + 1 >> numbers
            rm numbers.lock
        done
        break
    fi
done

根据您的要求,在启动脚本的新实例时,您可能实际上希望脚本删除文件中以前的任何值,但如果没有,则echo 0>编号也应受锁定文件的控制。

为什么要同时运行此脚本两次?为什么不使用安全的临时文件作为存储?请使用util中的flock-linux@EtanReisner这是一个问题,因此我们了解到存在比赛条件,需要避免它们。那么,您是否试图阻止您的脚本同时运行两次?不,我正在尝试确保它们都可以运行,防止竞争条件纠正-:现在已修复
#!/bin/bash
# FIXME: should properly lock here, too
if [ ! -f numbers ]; then echo 0 > numbers; fi
n=0
touch numbers
while [[ $n -lt 100 ]]; do
  if ln numbers numbers.lock
  then
    n=$(expr $(tail -1 numbers) + 1 | tee numbers)
    rm numbers.lock
  fi
done