避免複雜的管道檔案通訊,採用「預先掛起固定數量背景進程 → 監控存活數 → 動態分配任務」的輕量級模式。
#!/bin/bash
InDir="/in" OutDir="/out" CurCmd="varfixf"
du ${OutDir}; rm ${OutDir}/*; du ${OutDir}
totalInDir=`find ${InDir} -type f | wc -l`
curDir=`pwd`
if [ ! ${totalInDir} ]; then
echo "APP:MSG:There is no file in the in dir ... "; exit
else
echo "APP:MSG:Start to convert ... "
currentBinNum=0
find ${InDir} -type f | while read file; do
currentBinNum=`ps -ef | grep ${FEDX_HOME} | grep ${CurCmd} | grep ${curDir} | wc -l`
echo "APP:MSG:Backgroud num : ${currentBinNum}"
# 進程池上限控制(此處設 30,可自訂)
while [ ${currentBinNum} -gt 30 ]; do
sleep 1; echo 'sleeping ...'
currentBinNum=`ps -ef | grep ${FEDX_HOME} | grep ${CurCmd} | grep ${curDir} | wc -l`
done
filename=`basename $file`
varfixf ${curDir}/${InDir}/${filename} ${curDir}/${OutDir}/${filename} > /dev/null & # 背景執行
done
echo "APP:MSG:Convert over ... "
fi
ps -ef | grep ... | wc -l:統計當前掛起的目標進程數。while [ ${currentBinNum} -gt 30 ]; do sleep 1; ... done:達上限時暫停派發,輪詢等待釋放槽位。& 將任務丟入背景非阻塞執行,標準輸出導向 /dev/null。FEDX_HOME、CurCmd、目錄路徑均可依環境調整。批次檔案轉換、影像處理、資料匯入等「大量獨立任務、需限制併發度」的 Shell 自動化場景。