Killing a subtree of processes in linux bash

181 views Asked by At

i am typing a small bash script which should clone a git repository, checkout a specific hardcoded branch and listen for some new commits. If new commits are found the script should kill a running instance of 'MyApp', do a git pull and finally build it with gradle. It should also start via gradle again.

Yes it is a java application with a gradle build file.

This is my code:

##!/bin/bash

# GitHub Repository and Paths
GLOBAL_REPOSITORY="..."
LOCAL_REPOSITORY="..."

# Go to the repository
cd $LOCAL_REPOSITORY

# Clone the git repository if not already done
if [ ! -d "$LOCAL_REPOSITORY/.git" ]
then
  git clone $GLOBAL_REPOSITORY $LOCAL_REPOSITORY
  git checkout dev
fi

# Pull and build if there are new commits
LAST_GLOBAL_COMMIT=""
LAST_LOCAL_COMMIT=""

CHILDS_PID=""

while true; do
  git fetch origin

  LAST_GLOBAL_COMMIT="$(git rev-parse origin/dev)"
  LAST_LOCAL_COMMIT="$(git rev-parse dev)"

  if [ "$LAST_GLOBAL_COMMIT" != "$LAST_LOCAL_COMMIT" ]
  then
    if [ "$CHILDS_PID != "" ]
    then
      kill 9 "$CHILDS_PID" # Line 33
    fi

    LAST_LOCAL_COMMIT="$LAST_GLOBAL_COMMIT"

    git pull origin dev

    gradle

    CHILDS_PID="$(gnome-terminal -e \"gradle run\" & echo $!)"
  fi

  sleep 300
done

The problem which is occuring is that the child terminal and also MyApp are still running. Only gradle seems to die. But i want to kill all child processes and then run them again. Only the terminal which is running my script should not be killed.

In the actual situation the process tree should look like this:

Main Terminal (Running the script)
    |
    |
Child Terminal
    |
    |
Gradle run
    |
    |
MyApplication

My question is how can i kill all of these processes at once except the terminal on top in line 33?

EDIT:

The difference here is that i searched for a way to find the main node of a subtree and to kill it in the second step.

But i found out if a bash instance is calling a gnome-terminal or any other terminal or tty it is making a process which will initialize a forked off terminal.

So for example terminal_1 has a PID of 42 and i launch another terminal through it then it will start a init process with a PID of 43 which will initialize the terminal_2 which will have a PID of 44. But the terminal_1 gets only the 43 as a return value. After this the init process dies and if you try to kill PID 43 it logically says that there is no process with that PID.

At this point is tracking not possible and i solved my issue by writing a c program which uses fork at its own.

0

There are 0 answers