#! /bin/sh
# count2 also increments and appends a value to the numbers file
# but only when it can successfully create a new hard link to the numbers file
count=0
while [ $count -lt 200 ] # still loop 200 times
do
count=`expr $count + 1` # increment the loop counter
if ln numbers numbers.lock # try to enter the critical region
then # in this case, ln is similar to TSL
n=`tail -1 numbers` # get the last number to increment
expr $n + 1 >> numbers # increment it and append it to the file
rm numbers.lock # exit the critical region
fi # Note that if the ln was unsuccessful, we don't
# do busy waiting, but just continue looping
done
我的任务是在c中实现下面的shellcript,但我知道如何实现“如果ln数字numbers.lock#尝试进入临界区域“ 在c。脚本的功能是将它计数到200个,并将其输出到一个文件中,计算1-200的数字......我知道该怎么做,但棘手的部分是运行实现这个功能的ac程序,但运行同一个实例该程序在同一时间多次。这意味着所有的程序都会尝试写入相同的文件,从而产生非常无序的输出,例如:1 1 1 2 2 2 3 3 3 3 4 4 4例如!解决方法是实现一个锁,以便访问资源的程序在完成执行之前不会受到干扰,完成后,下一个程序可以在“后台”运行时使用该资源。我该怎么做呢?或者我如何复制特定的代码行?任何有用的资源参考将不胜感激,我一直在寻找,但我最终在阅读复杂的东西在C,我没有在C编程经验。为了清楚地说明问题:如何实现那些锁定是我主要关心的锁定。谢谢!使用单个程序在c中写入一个空文件,但同时运行它不止一次
3备注:1)LN默认创建硬链接,而不是符号链接(LN -s创建符号链接)2)使用链路系统调用由@misberner的建议比炮击了少了很多重手和3)flock确实是一个非常不错的选择,如果解决方案应该在具有较旧Linux内核的共享(nfs)文件系统上工作,请谨慎行事。 – fvu 2014-10-02 00:28:18
谢谢,我会修复地址#1的答案。 – 2014-10-02 06:06:29