I did a
strace on both commands. The interessting thing is that when you pipe the output to
head there are only 123 system calls. On the other hand when pipeing to tail there are 245 system calls (or more when there are more *.txt files).
Here are the last few lines when pipeing to
open("file12.txt", O_RDONLY) = 3
fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0
read(3, "", 16384) = 0
write(1, "0 file12.txt\n", 13) = -1 EPIPE (Broken pipe)
--- SIGPIPE (Broken pipe) @ 0 (0) ---
+++ killed by SIGPIPE +++
wc tries to write the output of the 12th file it gets an error
EPIPE. Thats why
head exited after getting the 11th line. When
SIGPIPE. As seen in the strace output above,
wc first tries to write to that pipe (where
head no longer reads from) and gets an error that the pipe is broken.
The SIGPIPE signal is sent to a process when it attempts to write to a
pipe without a process connected to the other end. -- from Wikipedia
When pipeing to
tail, there is nothing like that above. wc ends gracefully after writingall the output to the pipe where
tail needs to be connected to for the whole time.
tail needs all lines before it can print the last 10 of them. When there is no more output to read,
tail prints the lines and exits gracefully too