#! /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