send signal between scripts (bash)

2019-04-14 16:36发布

I've a little problem, probably it's a stupid question, but I started learning bash about a week ago... I have 2 script, a.sh and b.sh. I need to make both running constantly. b.sh should waits for a signal from a.sh

(I'm trying to explain: a.sh and b.sh run --> a.sh sends a signal to b.sh -> b.sh traps signal, does something --> a.sh does something else and then sends another signal --> b.sh traps signal, does something --> etc.)

This is what I've tried:

a.sh:

#!/bin/bash
./b.sh &;
bpid=$!;
# do something.....
while true
do
     #do something....
     if [ condition ]
     then
          kill -SIGUSR1 $bpid;
     fi
done

b.sh:

#!/bin/bash 
while true
do
     trap "echo I'm here;" SIGUSR1;
done

When I run a.sh I get no output from b.sh, even if I redirect the standard output to a file... However, when I run b.sh in background from my bash shell, it seems to answer to my SIGUSR1 (sent with the same command, directly from shell) (I'm getting the right output) What I'm missing?

EDIT: this is a simple example that I'm trying to run:

a.sh:

#!/bin/bash
./b.sh &
lastpid=$!;
if [ "$1" == "something" ]
then    
    kill -SIGUSR1 $lastpid;
fi

b.sh:

#!/bin/bash
trap "echo testlog 1>temp" SIGUSR1;
while true
do
    wait
done

I can't get the file "temp" when running a.sh. However if I execute ./b.sh & and then kill -SIGUSR1 PIDOFB manually, everything working fine...

1条回答
虎瘦雄心在
2楼-- · 2019-04-14 17:30

One of the possible solutions would be the next one (perhaps, it's dirty one, but it works):

a.sh:

#!/bin/bash

BPIDFILE=b.pid

echo "a.sh: started"
echo "a.sh: starting b.sh.."

./b.sh &
sleep 1

BPID=`cat $BPIDFILE`

echo "a.sh: ok; b.sh pid: $BPID"

if [ "$1" == "something" ]; then
    kill -SIGUSR1 $BPID
fi

# cleaning up..
rm $BPIDFILE

echo "a.sh: quitting"

b.sh:

#!/bin/bash

BPIDFILE=b.pid

trap 'echo "got SIGUSR1" > b.log; echo "b.sh: quitting"; exit 0' SIGUSR1

echo "b.sh: started"

echo "b.sh: writing my PID to $BPIDFILE"
echo $$ > $BPIDFILE

while true; do
    sleep 3
done

The idea is to simply write down a PID value from within a b (background) script and read it from the a (main) script.

查看更多
登录 后发表回答