how to control the multi_processor number
程序员文章站
2022-05-31 21:57:47
...
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)