首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Shell 多行程背景執行範例:進程池控制與動態任務分配

     編輯:關於.NET

設計理念

避免複雜的管道檔案通訊,採用「預先掛起固定數量背景進程 → 監控存活數 → 動態分配任務」的輕量級模式。

核心腳本邏輯

#!/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 自動化場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved