The question is the title. I couldn’t figure out why the terminal will shut down immediately after ‘ls’ is executed. A Linux shell is like this:
1.while (1) {
2. char *cmd = read_command();
3. int child_pid = fork();
4. if (child_pid == 0) {
5. exec(cmd);
6. }else {
7. waitpid(child_pid);
8. }
9.}
So, if we run ‘exec ls’ in shell, cmd is a string of ‘exec ls’. A child process is forked in line 3. In line 5, exec(cmd) will replace the child process but won’t affect the father process. If the father process is not affected, why the terminal shuts down then?
Please show me the flaws in my reasoning above.
If you run
ls, your shell process will start up another process to run thelsprogram, then it will wait for it to finish. When it finishes, control is returned to the shell.With
exec ls, you actually replace your shell program in the current process with thelsprogram so that, when it finishes, there’s no shell waiting for it.Most likely, you will have either a terminal program or
initas the parent which is what will take over when your process exits. That’s why your shell disappears, because you explicitly told it to.See this answer for an explanation of the
shell/ls(non-exec) situation.As for your update, the shell does not always create a separate process to do stuff. There are a large number of internal commands (such as
cdoralias) that do not involve making other processes (this depends on your shell, of course but, as one example, you can see thebashinternal commands by enteringman bash-builtinsat a command prompt).execis one of these. It simply replaces the shell itself (ie, not a forked child process) with the program you specify. That’s why it doesn’t act as you think.