Shared memory creation-chatgpt
Thu Jun 06 2024 14:04:58 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 a unique key for the shared memory segment
key = ftok(".", 'a');
// Create the shared memory segment
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 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);
}
// Write to the shared memory segment
s = shm;
for (char c = 'a'; c <= 'z'; c++) {
*s++ = c;
}
*s = '\0'; // Null-terminate the string
// Wait for the other process to read the data
while (*shm != '*') {
sleep(1);
}
// Detach the shared memory segment
if (shmdt(shm) == -1) {
perror("shmdt");
exit(1);
}
// Delete the shared memory segment
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}
return 0;
}
content_copyCOPY
Comments