gnu gnu - 5 months ago 9
Linux Question

How is it that a child process that calls exec() right after forking wouldn't need a separate copy of the parent's address space?

I am reading "Linux Kernel Development, Second Edition" by Robert Love. (Yes, it's a bit outdated). I understand from Chapter 3: Process Management that in COW (copy-on-write), the parent and child processes share the parent's address space until one of the processes writes to the address space. This is to prevent the unnecessary duplication of the parent's address space when it is not even being written to.

But then, it mentions that if the child process calls

exec()
right after
fork()
, the parent's address space and pages DON'T need to be copied and given to the child as a separate copy. That's where I'm lost.

According to the manual, "the exec() family of functions replaces the current process image with a new process image." The manual doesn't say anything about
exec()
creating a new address space for the new process image. So if the child process is sharing address space with its parent, wouldn't this mean that
exec()
would load an executable image into the parent's address space (which is shared with the child)?

Since that means the parent's address space would be overwritten, I don't understand how a child process that executes
exec()
after
fork()
WOULDN'T need a separate copy of its parent's address space to write to. Is there something I'm missing here?

Answer

Copy-on-Write mechanism implies, that none modification in child process will affect on parent.

Calling exec by the child is not an exception: it changes address space only for child, not for the parent.