简体   繁体   中英

How can I kill piped background processes?

Example session:

- cat myscript.sh 
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
# here is were I want tail and grep to die
echo "more code here"

- ./myscript.sh

- ps
  PID TTY          TIME CMD
15707 pts/8    00:00:00 bash
20700 pts/8    00:00:00 tail
20701 pts/8    00:00:00 grep
21307 pts/8    00:00:00 ps

As you can see, tail and grep are still running.


Something like the following would be great

#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"

But that only kills grep, not tail.

Although the entire pipeline is executed in the background, only the PID of the grep process is stored in $! . You want to tell kill to kill the entire job instead. You can use %1 , which will kill the first job started by the current shell.

#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"

Even if you just kill the grep process, the tail process should exit the next time it tries to write to standard output, since that file handle was closed when grep exits. Depending on how often example.log is updated, that could be almost immediately, or it could take a while.

you could add kill %1 at the end of your script.

That will kill the first background created, that way no need to find out pids etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM