shell中创建子进程只要用 & 操作符就行了,表示在后台运行.
可以利用wait 同步所有子进程结束.
实例代码如下:
#!/bin/sh
i=1
for i in `seq 10`
do
echo "$i"
multiply=`expr $i \* 10`
echo "multiply = $multiply"
sleep $multiply &
done
wait
例子中会创建10个子进程,每个进程各自sleep 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 second。
可以用 ps -aux |grep sleep 来查看进程状态。
xxha@PAF4:~/veex/ux400/upgrade$ ps -aux |grep sleep
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
xxha 3919 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 10
xxha 3921 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 20
xxha 3923 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 30
xxha 3925 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 40
xxha 3927 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 50
xxha 3929 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 60
xxha 3931 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 70
xxha 3933 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 80
xxha 3935 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 90
xxha 3937 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 100
xxha 3947 0.0 0.0 4384 828 pts/1 S+ 11:37 0:00 grep --color=auto sleep
等过个几十秒,各子进程慢慢结束
xxha@PAF4:~/veex/ux400/upgrade$ ps -aux |grep sleep
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
xxha 3929 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 60
xxha 3931 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 70
xxha 3933 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 80
xxha 3935 0.0 0.0 4200 284 pts/3 S+ 11:37 0:00 sleep 90
xxha 3937 0.0 0.0 4200 280 pts/3 S+ 11:37 0:00 sleep 100
xxha 3951 0.0 0.0 4384 832 pts/1 S+ 11:38 0:00 grep --color=auto sleep
最后全部结束:
xxha@PAF4:~/veex/ux400/upgrade$ ps -aux |grep sleep
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
xxha 3963 0.0 0.0 4384 828 pts/1 S+ 11:39 0:00 grep --color=auto sleep