0

I would like python3 command to exit when parent exits (after 10 seconds).

#! /bin/bash

sudo bash -c "python3 screen-buttons.py &"

sleep 10

printf "%s\n" "Done"
sunknudsen
  • 6,356
  • 3
  • 39
  • 76
  • 1
    Does this answer your question? [Bash: spawn child processes that quit when parent script quits](https://stackoverflow.com/questions/66537526/bash-spawn-child-processes-that-quit-when-parent-script-quits) – xhienne Apr 20 '21 at 15:38

1 Answers1

2

Well, you have to know the pid you want to kill, one way or the other.

#!/bin/bash

# assuming screen-buttons.py does not output anything to stdout
pid=$(sudo bash -c 'python3 screen-buttons.py & echo $!') 
sleep 10
kill "$pid"

If screen-buttons.py outputs something to stdout, save the pid to a file and read it from parent.

But it looks like you want to implement a timeout. If so see.. timeout utility.

To kill all descendant see https://unix.stackexchange.com/questions/124127/kill-all-descendant-processes

And anyway, why call bash and background in child process? Just call what you want to call.

#!/bin/bash
sudo python3 screen-buttons.py &
pid=$!
sleep 10
sudo kill "$pid"

and anyway:

sudo timeout 10 python3 screen-buttons.py
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 2
    This also has the problem that the `python3` process is run under `sudo` (so probably owned by root) so the calling script (probably not owned by root) can't kill it. – psmears Apr 20 '21 at 15:23
  • Thanks Kamil... `screen-buttons.py` doesn't output anything... it is essentially a loop listening to GPIO triggers. When I run command, `pid` has no value. – sunknudsen Apr 20 '21 at 15:28
  • I guess the loop inside Python script means `echo $!` is never called... – sunknudsen Apr 20 '21 at 15:33
  • `I guess the loop inside Python script means echo $! is never called` You guess seems wrong - the python script is run in the background with `&`, it's irrelevant what it does. `When I run command, pid has no value` Och right - quoting is wrong. Try now. But why are you are calling `bash` at all? – KamilCuk Apr 20 '21 at 15:45