how to control the multi_processor number

If you want to control the bash script’s multi process number.you can do like this
The really scene is to add user or delete user in your ubuntu os or ping the net in your computer.

#! /bin/bash

read -p "please input your prefix:" prefix

for i in {1..100}
do
        {
                sudo userdel $prefix$i 
                if [ $? -eq 0 ];then
                        echo "user $prefix$i is ok"
                else
                        echo "user $prefix$i failed"
                fi

        }&
done
wait
echo "all finished....."

if you type “bash multi.sh” in your terminal and hit the Enter key,you will find the number isn’t appear in sequence,but in a random order.

But unfortunately, if your computer is weird and can’t afford such heavy work.you can control the number of thread’s number.

please notice the change in the shell script below

#! /bin/bash
# ping 01
thread=5
tmp_fifofile=/tmp/$$.fifo #$$means the now process name
mkfifo $tmp_fifofile #make a named pipe file
exec 8<> $tmp_fifofile #allocate a file descriptor 8 to the file 
rm $tmp_fifofile
for i in `seq $thread`
do
        echo >&8 # to write a blank line to the file
done
ori_ip=192.168.2.
for i in {1..254}
do
        read -u 8 #to get the lock -u means get a file descriptor
        ip=$ori_ip$i
        {
                ping -c1 -W1 $ip &> /dev/null
                if [ $? -eq 0 ];then
                        echo "$ip is up"
                else
                        echo "$ip is down"
                fi
			    echo >&8  #to unlock the lock
        }&
done
wait
echo "all finished"
exec 8>&-    #to delete the file descriptor

if you execute this file you will notice that the result will return as five (which is equal to the thread you have set in the scripts)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值