一、編寫多進程實驗腳本 demo.shshell
#!/bin/bashbash
>sub1.log;>sub2.log;>sub3.log併發
function sub1ide
{函數
for i in {1..5}spa
do命令行
echo `date +%T` >> sub1.log #注意date 和+號之間有空格。如:date +%m/%d date取"月/日"的命令行。進程
sleep 1it
doneio
}
function sub2
{
for i in {1..5}
do
echo `date +%T` >> sub2.log
sleep 1
done
}
function sub3
{
for i in {1..5}
do
echo `date +%T` >> sub3.log
sleep 1
done
}
sub1
sub2
sub3
二、執行實驗腳本
[root@Svr23 Mornitor]# ./demo
[root@Svr23 Mornitor]# cat sub1.log
11:11:51
11:11:52
11:11:53
11:11:54
11:11:55
[root@Svr23 Mornitor]# cat sub2.log
11:11:56
11:11:57
11:11:58
11:11:59
11:12:00
[root@Svr23 Mornitor]# cat sub3.log
11:12:01
11:12:02
11:12:03
11:12:04
11:12:05
發現三個sub子函數是依次執行,總共須要15s
三、調整修改一下腳本,將sub子函數加入到後臺執行。
[root@Svr23 Mornitor]# vi demo.sh
..........
sub1&
sub2&
sub3&
再次執行實驗腳本
[root@Svr23 Mornitor]# ./demo
[root@Svr23 Mornitor]# cat sub1.log
11:12:24
11:12:25
11:12:26
11:12:27
11:12:28
[root@Svr23 Mornitor]# cat sub2.log
11:12:24
11:12:25
11:12:26
11:12:27
11:12:28
[root@Svr23 Mornitor]# cat sub3.log
11:12:24
11:12:25
11:12:26
11:12:27
11:12:28
發現三個sub子函數是並行執行,總共須要5s,速度大大提升
分析:shell是fork()+exec()來處理子命令,3個進程併發執行.主shell退出後,三個進程都會被init收養.