When creating a child process is it necessary to copy data from the parent process to the child process?

StackOverflow https://stackoverflow.com/questions/23170985

  •  06-07-2023
  •  | 
  •  

Question

I learned that,in linux fork() is used to create a new process. It allocates new memory for the child process then copies data from parent process to the child process such as file descriptors. Then exec() can be used to load its own data and overwrite the process space. But I wonder is it necessary to copy data of parent process to child process? How about loading the real data of a child process to its process space directly?

Was it helpful?

Solution

Read more about fork (system call), address space, virtual memory (the kernel is using the MMU), copy-on-write, processes ...

Read also Advanced Linux Programming. It has several chapters explaining these difficult concepts.

Parent and child processes have different address spaces, but after the fork the parent & child address spaces are nearly equal (thanks to virtual memory & copy-on-write techniques). The only difference being the result of the fork(2) syscall (which is [almost] the only way to create a process)

The execve(2) is entirely replacing the address space (and execution context) of its invoking process and is used to start a new executable program (often an ELF binary executable).

You don't need to copy data from parent to child process. The kernel is doing that magically for you.

You may want to do some inter-process communication (IPC) between parent and child, usually thru pipes (read pipe(7) & pipe(2) & poll(2)...), to be set up before the fork. You might want to use shared memory -avoid it if you are a newbie, since it is tricky to use correctly- but you should care about synchronization. See shm_overview(7) & sem_overview(7) for more.

Use also strace(1) and study the source code of some free software shell (like sash or bash)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top