==============================================================
  Experiment 05: IPC Using Shared Memory
==============================================================
  [Back to Index]
--------------------------------------------------------------

THEORY:
  Shared memory is the fastest IPC method.
  Processes directly read/write a common memory area.

  System Calls:
    shmget() - Create/access shared memory segment
    shmat()  - Attach shared memory to process
    shmdt()  - Detach shared memory
    shmctl() - Remove shared memory segment

--------------------------------------------------------------

PROGRAM 1: writer.c (Writer Process)

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

#define SHM_SIZE 1024

int main() {

    key_t key = 1234;

    int shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT);

    char *data = (char *)shmat(shmid, NULL, 0);

    char str1[100], str2[100];

    printf("Enter first string: ");
    scanf("%s", str1);

    printf("Enter second string: ");
    scanf("%s", str2);

    strcat(str1, str2);

    strcpy(data, str1);

    printf("Concatenated String Written to Shared Memory: %s\n", data);

    sleep(10);

    printf("Modified String from Process 2: %s\n", data);

    shmdt(data);

    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}
--------------------------------------------------------------

PROGRAM 2: reader.c (Reader Process)

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

#define SHM_SIZE 1024

int main() {

    key_t key = 1234;

    int shmid = shmget(key, SHM_SIZE, 0666);

    char *data = (char *)shmat(shmid, NULL, 0);

    printf("Received String: %s\n", data);

    for (int i = 0; data[i] != '\0'; i++) {

        if (islower(data[i]))
            data[i] = toupper(data[i]);

        else if (isupper(data[i]))
            data[i] = tolower(data[i]);
    }

    printf("Flipped Case String: %s\n", data);

    shmdt(data);

    return 0;
}
--------------------------------------------------------------

==============================================================
  [Prev: Exp 04]  |  [Next: Exp 06]
==============================================================