Unix & Linux
bash fork
Updated Fri, 20 May 2022 04:06:17 GMT

How exactly do programs or bash shell commands work on Linux systems?


I am researching how processes and shell work in Linux system. I would like to consult you to see if my conclusions are correct.

When we start the system, the kernel starts the init process, everything else is run as a sub-process with the fork of this process. For example, when I run any program, the parent process is forked for this program and then the forked process becomes the child process(or sub-process) that runs the program with exec. If this is the case, for example, when I run the bash shell, the parent process forked and exec makes the forked process the child process the bash program will run on. At this point, what stumbles upon me is how the commands we enter into the bash shell are executed. How do the built-in and external commands go through? For example, do built-in commands fork or create subprocesses for them?




Solution

What you are asking will be true for all Unixes, not just Gnu/Linux.

The thing to note is that after a fork, one does not need to exec. So for shell built-ins the shell will fork, and then do the built-in command.

The shell will also fork for a sub-shell. The shell does not fork when it does not have to: e.g. for simple commands that are built in. Where simple includes not in a pipeline.

There is also (not mentioned in your question) the pipes. These are created before the fork, but wired up after the fork, and before the, optional(see built-ins), exec.





Comments (1)

  • +0 – In addition, the expression "When the name of a built-in command is used as the first word of a simple command, the shell executes the command directly, without creating a new process." in the official source confused me a bit. After all, he uses the phrase "executes the command directly" here. Source: tldp.org/LDP/Bash-Beginners-Guide/html/sect_01_03.html — Oct 18, 2020 at 12:17