Bash: start and kill a child process

I have a program that I want to start. Say this program will run for some time (true) -loop (so it does not end. I want to write a bash script that:

  • Launches a program ( ./endlessloop &)
  • Waits for 1 second ( sleep 1)
  • Kills the program β†’ How?

I can not use $! to get the pid from the child, since the server works with many instances at the same time.

+4
source share
2 answers

Save PID:

./endlessloop & endlessloop_pid=$!
sleep 1
kill "$endlessloop_pid"

You can also check if the process continues to work with kill -0:

if kill -0 "$endlessloop_pid"; then
  echo "Endlessloop is still running"
fi

... and storing the contents in a variable means that it scales to several processes:

endlessloop_pids=( )                       # initialize an empty array to store PIDs
./endlessloop & endlessloop_pids+=( "$!" ) # start one in background and store its PID
./endlessloop & endlessloop_pids+=( "$!" ) # start another and store its PID also
kill "${endlessloop_pids[@]}"              # kill both endlessloop instances started above

. BashFAQ # 68: " ( -) N ?"

ProcessManagement Wooledge wiki .

+3

pgrep :

kill $(pgrep endlessloop)
0

Source: https://habr.com/ru/post/1655513/


All Articles