4

Consider the following contrived command:

cat /dev/urandom | wc -c

If you run it, cat sits and spins forever. If the process is killed with ^C, the whole pipeline will stop and wc will never show its count. In most cases, this is the desired and appropriate behavior.

Suppose I wanted to stop cat and still run wc -- in essence, count the number of characters that went through up until the process was killed. Is there a nice way to accomplish that without switching to another shell and running kill <PID of cat>?

smitelli
  • 6,835
  • 3
  • 31
  • 53

1 Answers1

3

You can stop job using Ctrl+Z:

$ cat /dev/urandom | wc -c
^Z
[1]+  Stopped                 cat /dev/urandom | wc -c
$

Now you can get list of processes in stopped job and kill process leader (cat, as you suggested in your question):

$ jobs -l
[1]+ 32164 Stopped                 cat /dev/urandom
     32165     

jobs -lp will output only id of a group leader:

$ jobs -lp
32164

You can kill it:

$ kill `jobs -lp`

and continue execution of wc:

$ fg
cat /dev/urandom | wc -c
71106560
rutsky
  • 3,900
  • 2
  • 31
  • 30
  • Yeah, that's similar to how I was initially trying to do it. I'm curious to see if the shell doesn't have a shorter way to send a SIGTERM directly to the leader without affecting the rest of the pipe. – smitelli Mar 09 '15 at 19:19