Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you run 'exec ls' in your shell and why? [closed]

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.

like image 604
zcb Avatar asked Dec 21 '22 10:12

zcb


2 Answers

If you run ls, your shell process will start up another process to run the ls program, 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 the ls program so that, when it finishes, there's no shell waiting for it.

Most likely, you will have either a terminal program or init as 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 cd or alias) that do not involve making other processes (this depends on your shell, of course but, as one example, you can see the bash internal commands by entering man bash-builtins at a command prompt).

exec is 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.

like image 141
paxdiablo Avatar answered Jan 14 '23 12:01

paxdiablo


Exec overrides the current process with another one. Normally when you call "ls" a new process is created that runs as child of your shell. "exec ls" overrides your current shell with the "ls" process. Thus as soon as "ls" terminates your terminal closes.

like image 29
bikeshedder Avatar answered Jan 14 '23 13:01

bikeshedder