博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

简单的shell多进程 (后台运行方式)

Posted on 2009-04-26 12:03  小易的博客园  阅读(4386)  评论(4)    收藏  举报

    这两天,因为工作地需要做一些的多进程的工作,看了网上的一些例子,多是通过管道文件的方式来实现的,后来想想也不用这么麻烦...

   下面是一个多进程后台挂起的一个简单的例子,原理大概如下,先在后台挂起一定数量的进程,当正在执行的进程数超过一定数值后,暂停任务分配,睡眠一定时间,若后台进程数小于你设定的数值后,继续任务分配。

   其实是不是也很简单...  

 

################ change the var bill to fix #########################################
################ change the pro to multi process ####################################
################ yijy 2009.4.26 modified ############################################
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}
        while [ ${currentBinNum} -gt 30 ] /*如果挂起数目大于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