After creating new processes using fork(), the memory of the parent and child processes is typically separate. In Linux or Unix-like systems, the child process created by fork() starts as an exact copy of the parent process, with the same memory image, but by default, this memory is separate due to the copy-on-write mechanism.
If you want to share memory between processes created by fork(), you can use the following methods:
1. Using POSIX Shared Memory Objects
POSIX shared memory is an effective way to share memory between different processes. You can use shm_open() to create a shared memory object, then use ftruncate() to adjust its size, and finally map it to the process's address space using mmap().
Example:
c#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/wait.h> int main() { const int SIZE = 4096; const char *name = "OS"; // Create shared memory object int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); ftruncate(shm_fd, SIZE); // Map shared memory object void *ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); pid_t pid = fork(); if (pid == 0) { // Child process char *message = "Hello, World!"; sprintf(ptr, "%s", message); exit(0); } else { // Parent process wait(NULL); printf("%s\n", (char *)ptr); shm_unlink(name); } return 0; }
In this example, the child process writes to the shared memory, and the parent process reads the same shared memory.
2. Using System V Shared Memory
System V shared memory is another form of shared memory supported on Linux systems. It uses shmget() to create a shared memory segment and shmat() to attach the shared memory segment to the process's address space.
3. Using File Mapping
You can also create a file and map it into memory to achieve inter-process shared memory. This can be done using mmap() without using shm_open() but directly operating on a regular file.
These methods can effectively share memory between processes created by fork(), with each method suitable for different scenarios and requirements. It is important to consider the specific application context and system resource limitations when choosing the appropriate shared memory method.