Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Start and kill child process

I have a program I want to start. Let' say this program will run a while(true)-loop (so it does not terminate. I want to write a bash script which:

  1. Starts the program (./endlessloop &)
  2. Waits 1 second (sleep 1)
  3. Kills the program --> How?

I cannot use $! to get pid from child because server is running a lot of instances concurrently.

like image 927
今天春天 Avatar asked Sep 22 '16 17:09

今天春天


People also ask

How do you kill a child's process?

For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.

How do you kill a process and a child process in Linux?

If it is a process group you want to kill, just use the kill(1) command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112 .

Does killing a process kill all child processes?

Killing a parent doesn't kill the child processes Every process has a parent. We can observe this with pstree or the ps utility. The ps command displays the PID (id of the process), and the PPID (parent ID of the process).


1 Answers

Store the PID:

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

You can also check whether the process is still running with kill -0:

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

...and storing the content in a variable means it scales to multiple 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

See also BashFAQ #68, "How do I run a command, and have it abort (timeout) after N seconds?"

The ProcessManagement page on the Wooledge wiki also discusses relevant best practices.

like image 196
Charles Duffy Avatar answered Oct 23 '22 11:10

Charles Duffy