Limiting the number of subshells spawned

徘徊边缘 提交于 2019-12-05 21:54:15

An easy way to limit the number of concurrent subshells to 10 is:

for ip in $(seq 1 255);do
  (<whatever you did with $ip in the subshell here, do with $network.$ip instead >) &
  if (( $ip % 10 == 0 )); then wait; fi
done
wait

With the last wait being useful not to let the subshells of the last round of the inner loop overlap with those created in first round of the next outer run.

I think I have found a better solution. I implemented using :

#!/usr/bin/make -f

IPFILE := ipfile
IPS:=$(foreach ip,$(shell cat $(IPFILE)),$(foreach sub,$(shell seq 1 1 254),$(ip).$(sub)))

all: $(IPS)

$(IPS):
        SYSNAME=`snmpwalk -v2c -c public -t1 -r1 $@ sysName.0 2>/dev/null | awk '{ print $$NF }'`; \
        SYSTYPE=`snmpwalk -v2c -c public -t1 -r1 $@ sysDescr.0 2>/dev/null | grep -o Linux`; \
        if [ $$? -eq 0 ]; then \
          echo "$$SYSNAME"; \
        else \
          echo "Processed $@"; \
        fi

The first part of the IPs (e.g. 192.168.1) should be placed to ipfile. Then it generates all the IP addresses into the variable IPS (Like 192.168.1.1 ... 192.168.1.254 ...).

These lines can be copied to e.g. test.mak and add execute rights to the file. If one run it as ./test.mak then it will process the IPs in IPS one by one. But if it is run as ./test.mak -j 10 then it will process 10 IPs at once. Also it can be run as ./test.mak -j 10 -l 0.5. It will run maximum 10 processes or until the system load reaches 0.5.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!