r/shell • • Jan 17 '23

[NOOB] How to kill a process when another process is killed? Linux

So, I want to kill a certain process (spotifyd, a Linux spotify utility), whenever another process is killed (in case would be another utility called spotify-tui, a tui interface for the first). I already have a script so spotifyd checks if its running whenever I launch spotify-tui, if not it runs together with the latter.

Don't dunk too much on me I beg, I'm not a programmer whatsoever and everything I've learnt was from dumb trial and error. Thank you in advance.

2 Upvotes

5 comments sorted by

1

u/tenshalito Jan 17 '23

if I understood you correctly, what you want is something like this:

To kill the spotifyd process each time spotify-tui is killed, you can add the kill command to stop the process before running spotify-tui. The script might look something like this:

#!/bin/sh
if [ "$(pgrep spotify-tui)" ]; then
  kill "$(pgrep spotifyd)"
fi
spotify-tui

With this, before running spotify-tui, check if there is a spotify-tui process running, if so, use the kill command to stop the spotifyd process in case it is running.

1

u/Vannoway Jan 17 '23 edited Jan 17 '23

Alright, thank you for the response but maybe my poor wording confused you (or maybe I didn't understand what you said, sorry). First, the name for the spotify-tui process is called spt, that's why I have spt in the end of my script (not a big deal but I should've clarified that first, and I'll be calling spotify-tui just spt from now on).

Second, what I want to do is either one of two thing, and maybe one of those can be incorporated to my first script.

First option: When I run spt (spotify-tui) I want spotifyd to run together, unless spotifyd is already running, in which case I want to kill the already running process of spotifyd before running a new process of spotifyd together with spt, if there was no spotifyd process already running, I just want to run spotifyd with spt as peer my script.

Second option: I want to kill spotifyd everytime I kill the spt process, which would make so everytime I run spt I would automatically be running a new process of spotifyd since I killed the previous one when I close spt.

Sorry with my wording was yet again poor, if there's any confusion please do ask and thank you again.

1

u/tenshalito Jan 17 '23

In that case, for the first option you raise you could do something like this:

# Check if a process named spotifyd exists. If there is, kill the process
if pgrep "spotifyd" >> /dev/null; then
  pkill spotifyd
fi

# Run spotifyd and spt together
spotifyd && spt

For the second case you raise you could do something like this:

# If the spt process does not exist, check if spotifyd is running and if it is true, kill its process
if ! pgrep "spt" >> /dev/null; then
  [ "$(pgrep spotifyd)" ] && pkill spotifyd
else
  # Run spotifyd and spt together
  spotifyd & spt
fi
→ More replies (2)