Why does the Bash shell run scripts in subshells? What is the advantage of doing so?
The shell, well, initially called the "user interface" of a system, was given the responsibility of executing programs (a.k.a tasks). To call a task, the shell would, in turn, ask the kernel to execute the task. The kernel manage the memory the task would use and the permissions to read or write to files. To ask the kernel to "execute" a program, the basic method is to fork a new task (which gives it a new PID (process number)) and then to exec the new program inside that new PID. The kernel would receive a list of arguments:
int execve(const char *filename, char *const argv[], char *const envp[]);
Basically asking the kernel to execute filename
with arguments argv[]
. The kernel does what is asked to do and when the program terminates the control returns to the parent process.
Taking the shell as the executor of programs, it is an obvious extension that it could also execute text files that some interpreter could understand. That is the mechanism of the shebang #! /interpreter
which the kernel also understand.
So, a shell could (and sometimes do) "execute an script", but the most natural execution sequence is to ask the kernel to do as with any other program: load the program and give it control of the process (PID).
It is expected that any program executed inside a different PID doesn't pollute the parent PPID. That is: changes in one PID doesn't affect the parent PID.
So, when "an script" gets executed it (usually) gets a new PID. Whether it is called subshell or a child shell is sometimes confusing, but what matters is that it runs inside a different PID. Usually a child process (PID).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다