m.frances
m.frances

Reputation: 23

Running two scripts and terminating one, when the other finishes

I have two scripts, one python and one c++. I need the python script to only run whilst the c++ script is active in the background, and then terminate at the same time. I have to do this as the python script contains an infinite loop which relies on the output of the C++ code. I'm a complete novice at this so I have written this bash script from answers I found here:

./test &
pid=$!

trap "kill -0 $pid 2> /dev/null" EXIT

while kill -0 $pid 2> /dev/null; do
        python display.py
done

trap - EXIT

but it fails to actually terminate the python script and it just keeps looping until I manually kill the process. I'm using ubuntu 18.04.1 if that's useful.

Upvotes: 2

Views: 331

Answers (2)

pjh
pjh

Reputation: 8064

Bash, in common with other shells, has a built-in wait command to wait for background commands to exit. Unless your top-level program needs to do other things while the other programs are running, you can simply run both of them in the background, wait for the first one to finish, and then kill the second one:

#! /bin/bash

./test &
testpid=$!

python display.py &
pythonpid=$!

wait "$testpid"

printf "Killing 'display.py' (PID %d)\\n" "$pythonpid" >&2
kill "$pythonpid"

If it would work to run the Python program before the C++ program then a simpler option is:

#! /bin/bash

python display.py &
pythonpid=$!

./test

printf "Killing 'display.py' (PID %d)\\n" "$pythonpid" >&2
kill "$pythonpid"

Upvotes: 0

Tyler Marshall
Tyler Marshall

Reputation: 488

The issue is this part:

while kill -0 $pid 2> /dev/null; do
    python display.py
done

Once the python display.py starts, the script stops and waits for it to finish. This means it is no longer executing the kill -0 command. You can start the display.py command if the other process starts, and then kill it when the C program finishes.

./test &
pid=$!

if kill -0 $pid 2>/dev/null; then
  #c program started
  python display.py &
  python_pid=$!

  while kill -0 $pid 2>/dev/null; do
    #c program running
    sleep 1;
  done
  #c program finished
  kill $python_pid
fi

That being said, I agree with @Poshi. The better way to do this would be to use pipes. Since the python program is reading from the c program, you should do something like ./test.sh | python display.py. The above answer is more of "how to hack the method you were already trying".

Upvotes: 1

Related Questions