The kernel has to initialize the virtual address space of a process, creating the .text, .bss, .data, heap, and stack segments.
If a process creates a thread, a new segment must be added to the virtual address space for a stack for the thread.
The mmap system call can create new mappings; that is, can add a new segment at some virtual address space of the process.
#include <unistd.h> #include <sys/mman.h> void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *start, size_t length); prot: PROT_EXEC, PROT_READ, PROT_WRITE, PROT_NONE flags: MAP_PRIVATE, MAP_SHARED, MAP_ANON
- PROT_EXEC Pages may be executed.
- PROT_READ Pages may be read.
- PROT_WRITE Pages may be written.
- PROT_NONE Pages may not be accessed.
- MAP_PRIVATE Private copy-on-write mapping
- MAP_SHARED Share with all other processes
- MAP_ANONYMOUS Not associated with a file (only used with MAP_PRIVATE)
MAP_PRIVATE | MAP_ANON could be used to map an area of virtual memory for a stack segment for a new thread.
Copy-on-write is also used in the implementation of fork.