In the following link, and in many others like it, exec is often described as:
Differences between fork and exec
The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.
Does it really replace the entire program though? Isnt it just more like executing a subroutine/function call that just happens to embody the main() of the selected program? - before returning back into its own context and operations?
so wouldnt a more appropriate description be, just a subroutine that embodies main()? (e.g. incorporating the chosen processes code into the current proccesses? As opposed to full on "replacing it"?
# original taken from the provided link
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | ls |
V +--------+
+--------+ |
| pid=7 | | exits
| ppid=4 | <---------------+
| bash |
+--------+
|
| continues
V
# wouldnt this technically be more accurate?
# or am I misunderstanding something with exec()?
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | bash |
| | ls() |
| +--------+
| |
| | ls completes
| | and the program context returns to bash's
| |
| +--------+
| | pid=22 |
| | ppid=7 |
| | bash |
| +--------+
| |
V |
+--------+ | the child branch of bash calls exit/return
| pid=7 | | that follows the exec statement in the
| ppid=4 | <---------------+ "if (fork() == 0) {...}" code branch
| bash |
+--------+
|
| continues
V
Now obviously there is a flaw in my understanding. Since if what I have said above is correct, then shouldnt all spawned proccesses be all just instances of bash or init when I look into htop? They arent (they all have their own names e.g. ls or htop) So does exec() actually replace the entire program that calls it w/ a new one? So like calling exec() implicitly kills the program which calls it? What is going on here?