Question: If I run these commands:

```
dmesg | head -n 10

```

I presume the OS sends back some kind of signal to `dmesg` once `head` has read 10 lines. How does this work? What does `head` tell the kernel?

This is different from a program dying since this is a normal, 'clean' stop.

Answer: 
It depends on the OS buffers and the timing between the 10th and 11th writes of `dmesg`.

After `head` writes 10 lines, it terminates and `dmesg` will receive [SIGPIPE signal](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html#tag_13_42_03) if it continues writing to the pipe.

Depending on your OS buffer, `dmesg` will often write more than 10 lines before `head` consumes them.

To see that `head` had consumed more than 10 lines, you can use:

```
strace -f sh -c 'dmesg | head -n 10'

```

(Look at the `head` process, count on number of `read` system calls.)

To see how the writing speed effect:

```
strace -f sh -c "perl -le '$|++;print 1 while 1' | head -n 10"

```
`head` closes *stdin* after printing 10 lines. Then `dmesg` detects that the *stdout* is closed and exits.

To be more precise, `dmesg` will receive the `EPIPE` error from the `write` call to *stdout*.

From the *dmesg.c* source code here: <https://github.com/karelzak/util-linux/blob/v2.27.1/sys-utils/dmesg.c#L654-L659>

```c
rc = fwrite(p, 1, len, out) != len;
if (rc != 0) {
    if (errno != EPIPE)
        err(EXIT_FAILURE, _("write failed"));
    exit(EXIT_SUCCESS);
}

```