Inter-Process Communication Using Shared Memory
1️⃣ What is Shared Memory?
Shared memory is an IPC mechanism where multiple processes access the same physical memory region.

Fastest IPC mechanism

No kernel involvement after setup

Requires explicit synchronization (semaphores/mutex)

2️⃣ Why Shared Memory?
✔ Very high performance
✔ Suitable for large data sharing
❌ Risk of race condition without synchronization

3️⃣ System Calls Used (System V Shared Memory)
Function	Purpose
ftok()	        Generate IPC key
shmget()	        Create shared memory
shmat()	        Attach shared memory
shmdt()	        Detach shared memory
shmctl()	        Control / delete memory
4️⃣ Communication Model (Simple Example)
Parent process writes data

Child process reads data

Shared memory is created before fork()

5️⃣ Small Example: Parent Writes, Child Reads
🔹 Program Explanation
Create shared memory

Fork child

Parent writes message

Child reads message

Shared memory deleted

6️⃣ C Program: Shared Memory IPC
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

int main() {
    key_t key;
    int shmid;
    char *shared_mem;

    // Generate unique key
    key = ftok("shmfile", 65);

    // Create shared memory segment (1024 bytes)
    shmid = shmget(key, 1024, 0666 | IPC_CREAT);

    // Attach shared memory
    shared_mem = (char*) shmat(shmid, NULL, 0);

    if (fork() == 0) {
        // Child process
        sleep(1);  // ensure parent writes first
        printf("Child reads: %s\n", shared_mem);
        shmdt(shared_mem);
    } else {
        // Parent process
        strcpy(shared_mem, "Hello from parent via shared memory");
        printf("Parent writes message\n");
        wait(NULL);
        shmdt(shared_mem);
        shmctl(shmid, IPC_RMID, NULL);  // delete shared memory
    }

    return 0;
}
7️⃣ Sample Output
Parent writes message
Child reads: Hello from parent via shared memory
8️⃣ Important Notes 
Shared memory is not synchronized by default

Race conditions may occur

Use semaphores for synchronization

Must remove shared memory using shmctl()


Explanation of Functions Used in Shared Memory IPC Program
The program uses System V shared memory and a few process control system calls.

1️⃣ ftok() — Generate IPC Key
Prototype
key_t ftok(const char *pathname, int proj_id);
Purpose
Generates a unique key used to identify the shared memory segment.

Arguments
Argument	Description
pathname	                Existing file name
proj_id	                Project identifier (character or number)
Example
key = ftok("shmfile", 65);
📌 Note:
Both processes must use the same key to access shared memory.

2️⃣ shmget() — Create or Access Shared Memory
Prototype
int shmget(key_t key, size_t size, int shmflg);
Purpose
Creates a shared memory segment or accesses an existing one.

Arguments
Argument	Description
key	            IPC key
size	            Size of shared memory in bytes
shmflg	            Permission and flags
Example
shmid = shmget(key, 1024, 0666 | IPC_CREAT);
Flags Explained
0666 → Read/write permissions

IPC_CREAT → Create segment if not present

3️⃣ shmat() — Attach Shared Memory
Prototype
void *shmat(int shmid, const void *shmaddr, int shmflg);
Purpose
Attaches shared memory to the process’s address space.

Arguments
Argument	Description
shmid	                    Shared memory ID
shmaddr	                    Address to attach (NULL = system chooses)
shmflg	                    Access mode (0 = read/write)
Example
shared_mem = (char*) shmat(shmid, NULL, 0);
📌 Return Value

Pointer to shared memory

(void *) -1 on failure

4️⃣ fork() — Create Child Process
Prototype
pid_t fork(void);
Purpose
Creates a child process that shares the same memory segment.

Return Values
Return	            Meaning
0	            Child process
>0	            Parent process
<0	            Error
Example
if (fork() == 0) { /* child */ }
5️⃣ strcpy() — Write to Shared Memory
Prototype
char *strcpy(char *dest, const char *src);
Purpose
Copies message into shared memory.

Example
strcpy(shared_mem, "Hello from parent");
📌 Important:
Shared memory behaves like normal memory.

6️⃣ sleep() — Delay Execution
Prototype
unsigned int sleep(unsigned int seconds);
Purpose
Ensures parent writes first before child reads.

Example
sleep(1);
7️⃣ shmdt() — Detach Shared Memory
Prototype
int shmdt(const void *shmaddr);
Purpose
Detaches shared memory from process address space.

Arguments
Argument	Description
shmaddr	Address returned by shmat()
Example
shmdt(shared_mem);
8️⃣ shmctl() — Control / Delete Shared Memory
Prototype
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
Purpose
Controls shared memory segment.

Arguments
Argument	Description
shmid	Shared memory ID
cmd	Control command
buf	Optional structure
Example
shmctl(shmid, IPC_RMID, NULL);
Commands
Command	Meaning
IPC_RMID	Remove shared memory
IPC_STAT	Get status
9️⃣ wait() — Wait for Child Process
Prototype
pid_t wait(int *status);
Purpose
Ensures parent waits for child before deleting memory.

Example
wait(NULL);
🔹 Summary Table (Quick Revision)
Function	Purpose
ftok()	        Generate key
shmget()	        Create shared memory
shmat()	        Attach memory
fork()	        Create child
strcpy()	        Write data
shmdt()	        Detach memory
shmctl()	        Delete memory
wait()	        Synchronize parent
