Posted on 2009-03-13 16:32
Prayer 阅读(1299)
评论(0) 编辑 收藏 引用 所属分类:
Shell
今天看到一个shell脚本玩多进程的例子,觉得很有趣扩展一下代码。
#!/bin/bash Number="1000"; Thread="10"; Timeout="1"; PATH="${PATH}:/sbin:/usr/sbin"; function RunCmd() { echo "User Cmd" } function LockFile() { find /dev/shm/* -maxdepth 0 -type l -follow -exec unlink {} \; [ -f /dev/shm/${0##*/} ] && { echo "$0 is run !";exit 1; } ln -s /proc/$$ /dev/shm/${0##*/} trap "Exit" 0 1 2 3 15 22 24 } function Exit() { unlink /dev/shm/${0##*/}; ps -eo "%p %P %c"|awk '{if($2==1 && $3~/'${0##*/}'/)system("kill -9 "$1)}' exec 4<&-; rm -f ${PID} exit 0; }
# main () LockFile PID="$$"; cd /dev/shm/;exec 2>/dev/null typeset i; ( while true;do sleep $((${Timeout}+3)); ps -eo "%p %P %t"|awk '{if($2=='${PID}') { split($3,ST,"[^0-9]"); L=length(ST); S=0; if(L==4){ S=ST[1]*86400;ST[1]=0 } for(a=L;a>0;a--) S=S+(ST[a]*(60**(L-a))); if(S>'${Timeout}') { system("kill -9 "$1" && echo N >'${PID}'")} }}' done & >/dev/null 2>&1 ) mknod ${PID} p ;exec 4<>${PID} for((i=0;i<Thread;i++));do echo "OK" >&4;done for((i=0;i<Number;i++));do read; ( RunCmd; echo "OK" >&4 ) & done <&4 wait
|