Is there any way to count the lines of a non-terminating input source? For example, I want to run the following for a period of time to count the number of requests:
ngrep -W byline port 80 and dst host 1.2.3.4 | grep ":80" | wc
Obviously, that doesn't work. When I Ctrl+C kill that, I'm not going to get any output from wc
. I would rather avoid creating a file if I can.
Best Answer
Typing Ctrl+C from the terminal sends
SIGINT
to the foreground process group. If you wantwc
to survive this event and produce output, you need to have it ignore the signal.The solution is to run
wc
in a subshell and have its parent shell setSIGINT
to be ignored before runningwc
.wc
will inherit this setting and not die whenSIGINT
is sent to the process group. The rest of the pipeline will die, leavingwc
reading from a pipe that has no process on the other end. This will causewc
to seeEOF
on the pipe and it will then output its counts and exit.