Shared memory reading-chatgpt
Thu Jun 06 2024 14:06:51 GMT+0000 (Coordinated Universal Time)
Saved by
@exam123
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 // Size of shared memory segment
int main() {
int shmid;
key_t key;
char *shm, *s;
// Generate the same unique key used by the other program
key = ftok(".", 'a');
// Locate the shared memory segment
shmid = shmget(key, SHM_SIZE, 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}
// Attach the shared memory segment
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1) {
perror("shmat");
exit(1);
}
// Read from the shared memory segment
for (s = shm; *s != '\0'; s++) {
putchar(*s);
}
putchar('\n');
// Signal to the other process that we've finished reading
*shm = '*';
// Detach the shared memory segment
if (shmdt(shm) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
content_copyCOPY
Comments