20

Basically I want to dynamically start some processes which may create their own children processes, also I want to kill a certain group of processes I just created whenever I want.

One way I could think of is to start processes with a name (to distinguish as a group), then use pkill to kill them by the name.

The question is how to start a process with a name so that I can use pkill to kill them by the name? I am open to other solutions as well.

Eric Carvalho
  • 55,453
cache
  • 1,541

3 Answers3

18

You can use the exec shell builtin:

bash -c "exec -a MyUniqueProcessName <command> &"

<command> replaces the current shell, no new process is created, that's why I'm starting a new shell to call exec.

Then you can kill the process with:

pkill -f MyUniqueProcessName

You can start more than one process under the same name, then pkill -f <name> will kill all of them.

Eric Carvalho
  • 55,453
1

AMItac / The Solaris Agency

I had an issue with an audio transcoding tool that ran 3 times under the same name.

I did following. Went to the bin directory and copyied the transcoding script 3 times and gave each one a new name. tc-1 , tc-2 , tc-3 (it´s a small tool so it doesn't eat much drive space (with large binaries you shouldn't use this method)

so the process started with an unique Name and can be killed with this unique Name without the danger of killing other transcoding processes i want to continue.

another trick MIGHT work....

add a #bash script Name.sh, make it executable. Type in your commands there and start the bash script itself. On Centos it uses then the Bashscript Name you excecuted and not the bin Name itself.

Hope something helps someone out there.

Riley
  • 139
0

Here is the Python solution I use. Obviously there is a slight startup time and memory overhead, but aside from that it does the job. It uses the setproctitle module, which you can install via python -m pip install setproctitle

#!/usr/bin/env python
'''
example:
launch_with_name HelloWorld sleep 10
'''

from setproctitle import setproctitle # python -m pip install setproctitle from subprocess import run import sys args = sys.argv[1:] if len(args) < 2: print(f"Not enough arguments") print(f"{sys.argv[0]} <process name> <command> [<args> ...]") exit(1) setproctitle(args[0]) cmd = args[1:] exit(run(cmd).returncode)