Reputation:
We know that each time a user runs a program by typing the name of an executable object file to the shell, the shell creates(use fork
) a new process and then loads(use execve
) and runs the executable object file in the context of this new process.
Below is my understanding of how a shell works internally, please correct me if I was wrong:
Commands such as
ls
,cat
etc are executable objects (source file written by C) are in/bin/
directory. for example, when a user type in bash shellls
to list files and directories, the bash shell intepretsls
command and fork a child process to runls
Q1-Is my understanding correct?
Q2-if my understanding is correct, then when a shell run .sh script file which is:
#!/bin/sh
echo "what is your name?"
read name
so the shell forks two child processes for echo
and read
, then how does these two processes communicate with each other? I mean how does the return output of echo
process get passed to read
process?
Upvotes: 0
Views: 402
Reputation: 141010
Is my understanding correct?
Generally, yes. But the executable file not necessarily is in /bin/
. A file named ls
is searched in paths specified inside PATH
environment variable and the match is used. The file can be in /usr/bin
/usr/sbin
/usr/local/bin
etc.
And ls
may be a builtin. Or a function. Or an alias.
so the shell forks two child processes for echo and read
And this is where a "built-in" comes in. A built-in is an internal part of the shell handled internally by the shell. There is no fork
, just some internal code is run and that way it can modify the environment variables. echo
not necessarily is a builtin, it only outputs data. But read
has to be handled specially and most probably is a builtin for it to modify name
variable (there is no requirement for read to be builtin, it may not be, but usually shell writers solve this problem by just making read
a builtin).
On bash
you can check the type of command with type
. Ex. type echo
shows echo is a shell builtin
.
I mean how does the return output of echo process get passed to read process?
It doesn't.
You may want to read posix Command Search and Execution.
Upvotes: 2