Shared memory writer

PHOTO EMBED

Thu Jun 06 2024 01:01:56 GMT+0000 (Coordinated Universal Time)

Saved by @login

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

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

    // Generate unique key
    key = ftok("shmfile", 65);
    if (key == -1) {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    // Create shared memory segment
    shmid = shmget(key, 1024, 0666 | IPC_CREAT);
    if (shmid == -1) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    // Attach shared memory segment
    str = (char*) shmat(shmid, NULL, 0);
    if (str == (char*) -1) {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    // Write to shared memory
    printf("Write Data: ");
    fgets(str, 1024, stdin);

    // Detach shared memory segment
    if (shmdt(str) == -1) {
        perror("shmdt");
        exit(EXIT_FAILURE);
    }

    return 0;
}
content_copyCOPY