writerprocess
Fri Jun 07 2024 04:53:54 GMT+0000 (Coordinated Universal Time)
Saved by
@prabhas
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main() {
// Generate unique key
key_t key = ftok("shmfile", 65);
if (key == -1) {
perror("ftok");
return 1;
}
// Create shared memory segment
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
if (shmid == -1) {
perror("shmget");
return 1;
}
// Attach to shared memory
char *str = (char*)shmat(shmid, (void*)0, 0);
if (str == (char*)(-1)) {
perror("shmat");
return 1;
}
// Write data to shared memory
printf("Write Data : ");
fgets(str, 1024, stdin);
// Remove the newline character added by fgets
str[strcspn(str, "\n")] = 0;
printf("Data written in memory: %s\n", str);
// Detach from shared memory
if (shmdt(str) == -1) {
perror("shmdt");
return 1;
}
return 0;
}
content_copyCOPY
Comments