Fundamentals 7 min read

Mastering Linux Shared Memory IPC: Theory, API Calls, and a Complete Example

This article explains the principles of Linux shared memory interprocess communication, details the relevant data structures and system limits, walks through the essential API calls for creating, controlling, attaching, and detaching shared memory, and provides a full C program demonstrating parent‑child communication.

ITPUB
ITPUB
ITPUB
Mastering Linux Shared Memory IPC: Theory, API Calls, and a Complete Example

Shared Memory IPC Principle

Shared memory is a region of RAM that can be mapped into multiple processes. The kernel represents each segment with struct shmid_ds containing permission bits, size, timestamps, creator and last‑operator PIDs, and attachment count.

struct shmid_ds {
    struct ipc_perm shm_perm;   /* operation permissions */
    int               shm_segsz; /* segment size in bytes */
    __kernel_time_t   shm_atime;/* last attach time */
    __kernel_time_t   shm_dtime;/* last detach time */
    __kernel_time_t   shm_ctime;/* last change time */
    __kernel_ipc_pid_t shm_cpid;/* creator PID */
    __kernel_ipc_pid_t shm_lpid;/* last operator PID */
    unsigned short    shm_nattch;/* current attach count */
    unsigned short    shm_unused;/* compatibility */
    void *            shm_unused2;
    void *            shm_unused3;
};

The kernel enforces limits such as SHMMAX (maximum segment size), SHMMIN (minimum size), SHMMNI (maximum number of segments system‑wide), and SHMSEG (maximum segments per process).

Linux Shared Memory Management

1. Create a shared memory segment

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

int shmget(key_t key, size_t size, int shmflg);
key

is typically generated with ftok(). size is the desired segment size in bytes. shmflg includes IPC_CREAT and permission bits.

2. Control the segment

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

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

3. Attach the segment

#include <sys/types.h>
#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

If shmaddr is zero, the kernel chooses the mapping address. shmflg can specify read/write permissions.

4. Detach the segment

#include <sys/types.h>
#include <sys/shm.h>

int shmdt(const void *shmaddr);

After a process finishes using the segment, it should call shmdt() with the address returned by shmat().

Parent‑Child Conventions

After fork(), the child inherits all shared memory segments attached by the parent.

If the child later calls exec(), all attached shared memory is automatically detached.

Calling exit() in a process detaches its shared memory segments.

Example Program

The following program creates a shared memory segment, writes an integer in the parent, forks a child that reads the value, then cleans up.

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define SHM_SIZE 1024

int main() {
    int shm_id, pid;
    int *ptr = NULL;

    /* Create shared memory */
    shm_id = shmget((key_t)1004, SHM_SIZE, IPC_CREAT | 0600);
    if (shm_id < 0) { perror("shmget"); exit(1); }

    /* Attach shared memory */
    ptr = (int*)shmat(shm_id, 0, 0);
    if (ptr == (void*)-1) { perror("shmat"); exit(1); }
    printf("Attach addr is %p
", ptr);

    *ptr = 1004;
    printf("Parent value: %d
", *ptr);

    if ((pid = fork()) == -1) {
        perror("fork"); exit(1);
    } else if (pid == 0) {   /* child */
        printf("Child value: %d
", *ptr);
        exit(0);
    } else {                  /* parent */
        sleep(1);
    }

    /* Detach and remove */
    shmdt(ptr);
    shmctl(shm_id, IPC_RMID, 0);
    return 0;
}

Typical output shows the parent writing the integer and the child reading the same value.

Program output showing parent and child values
Program output showing parent and child values
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Linuxshared memoryIPCC programmingInterprocess CommunicationPOSIX
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.