0

Bash builtins defines as:

The shell executes the command directly, without invoking another program.

And a pipeline like foo | bar works roughly like: bar waits inputs from foo, and foo exits first, and then bar exit.

In bash a pipeline like this works as expected:

$ history | grep curl

But how can grep manage to know history is done its work, and exits itself? Since history, which is a builtin, was not spawning new process. Does history generate an EOF signal or something?

  • the shell runs each command from a pipeline in a separate process, no matter if it's an external command or a built-in. So yes, history | ... is spawning a new process, even if it's just another instance of bash. – mosvy Sep 25 '18 at 4:17
1

When the manual says "without invoking another program", it means that the shell doesn't use execve to execute another programs. When a command uses redirection, the simple implementation is to fork another process and do the redirection for that process only, leaving the file descriptors of the parent shell unmodified. This is also what bash does with this command, as can be verified with strace.

It is possible to do some trickery and avoid the forks for internal commands, but it seems they are not used in this case.

The second program can't detect that the first program exits, it can only detect that the output side of the pipe has been closed (which may happen because the program exited, or because of a regular close). The reading side of the pipe will receive an EOF.

It is common but not necessary for the first program in a pipe to exit first. Consider:

sleep 10 | echo done

If the second program of the pipe exits before the first and the first tries to write to the pipe it will get the signal SIGPIPE, which will terminate the process, unless it is caught.

(sleep 10; echo test ) | echo done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.