我想写两个相互发送信号的脚本,比如一个乒乓球比赛,但是有一个信号,而不是一个球。
第一个脚本:
.md
第二个脚本(player2pp.sh):
#!/bin/bash
PATH=${PATH}:"/home/cosimo/Università/Sistemi Operativi/scripts"
exec player2pp.sh $$ &
trap "kill -SIGUSR1 $pidp2" SIGUSR1
sleep 2
我在#!/bin/bash
trap "kill -SIGUSR1 $1" SIGUSR1
sleep 2
kill -SIGUSR1 $1
sleep 2
:
kill:没有相应的过程。
我做错了什么?
答案 0 :(得分:3)
一些问题:
exec
此外,我会为陷阱编写一个函数,以便更容易进行日志记录:
player1pp.sh
#!/bin/bash
cd "/home/cosimo/Università/Sistemi Operativi/scripts"
./player2pp.sh $$ &
pidp2=$!
_ping() {
echo "ping! killing $pidp2"
kill -SIGUSR1 $pidp2
}
trap _ping SIGUSR1
trap "kill $pidp2" EXIT
while true; do sleep 2; done
player2pp.sh
#!/bin/bash
pidp1=$1
_pong() {
echo "pong! killing $pidp1"
kill -SIGUSR1 $pidp1
}
trap _pong SIGUSR1
_pong # start the game
while true; do sleep 2; done
为了好玩,添加一些随机性:
玩家1
#!/bin/bash
cd "/home/cosimo/Università/Sistemi Operativi/scripts"
./player2pp.sh $$ &
opponent=$!
ping() {
sleep=$((RANDOM % 5))
echo "ping! killing $opponent in $sleep"
sleep $sleep
kill -USR1 $opponent
}
trap ping USR2
cleanup () {
kill -0 $opponent && kill $opponent
}
trap cleanup EXIT
ping
while :; do :; done
玩家2
#!/bin/bash
opponent=$1
pong() {
sleep=$((RANDOM % 5))
echo "pong! killing $opponent in $sleep"
sleep $sleep
kill -USR2 $opponent
}
trap pong USR1
cleanup () {
kill -0 $opponent && kill $opponent
}
trap cleanup EXIT
while :; do :; done