Home > Software engineering >  run bash script in background with process name
run bash script in background with process name

Time:02-20

Got a script for activating a python venv and running a server in the background, but right now I am trying to keep the pid when I start the process and then kill the process with pid after I am done. However, it is not all the time is gets killed.

My question is, can I run the process with a name, then killing it by using pkill name after? and how will that look


#!/bin/sh

ROOT_DIR=$(pwd)

activate(){
    source $ROOT_DIR/.venv/bin/activate
    python3 src/server.py -l & pid=$!     # <== This is the process
    python3 src/client.py localhost 8080
}

activate
sleep 10
kill "$pid"

printf "\n\nServer is done, terminating processes..."

CodePudding user response:

You can run programs with a specific command name by using the bash buildin exec. Note that exec replaces the shell with the command so you have to run it in a subshell environment like:

( exec -a my_new_name my_old_command ) &

However, it probably won't help you much because this sets the command line name, which is apparently different from the command name. So executing the above snippet will show your process as "my_new_name" for example in top or htop, but pkill and killall are filtering by the command name and will thus not find a process called "my_new_name".

While it is interesting, how one can start a command with a different name than the executable, it is most likely not the cause of your problem. PIDs never change, so I assume that the problem lays somewhere different.

My best guess is that the server binds a socket to listen on a specific port. If the program is not shutdown gracefully but killed the port number remains occupied and is only freed by the kernel after some time during some kind of kernel garbage collect. If the program is restarted after a short period of time it finds the port already been occupied and prints a misleading message, that says it is already running. If that is indeed the cause of your problem I would strongly consider implementing a way to graceful shutdown the server. (may be already closing the socket in a destructor or something similar could help)

CodePudding user response:

I think you should have to use systemd for this case: https://github.com/torfsen/python-systemd-tutorial

  • Related