Sobes.tech
Junior — Middle

What mechanism is responsible for creating shared memory segments for processes?

sobes.tech AI

Answer from AI

The mechanism responsible for creating shared memory segments for processes is called Shared Memory. In operating systems like Unix/Linux, this is implemented through system calls such as shmget, shmat, shmdt, and shmctl.

Shared Memory allows multiple processes to share the same memory segment, significantly speeding up data exchange compared to other inter-process communication (IPC) methods.

An example in C (simplified):

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>

int main() {
    key_t key = 1234; // unique key
    int shmid = shmget(key, 1024, 0666|IPC_CREAT); // create memory segment
    char *data = (char*) shmat(shmid, NULL, 0); // attach segment

    strcpy(data, "Hello from shared memory!");
    printf("Data in shared memory: %s\n", data);

    shmdt(data); // detach segment
    // shmctl(shmid, IPC_RMID, NULL); // delete segment if needed
    return 0;
}