Shared mem GPT
tuhuuduc
c_cpp
2 years ago
1.6 kB
8
Indexable
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <sys/wait.h>
int main() {
// Key to identify the shared memory segment
key_t key = ftok("/tmp", 'S'); // You may use any valid path and id
// Size of the shared memory segment
size_t size = sizeof(int);
// Create a shared memory segment
int shmid = shmget(key, size, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}
// Attach to the shared memory segment
int *shared_memory = (int *)shmat(shmid, NULL, 0);
if (shared_memory == (int *)(-1)) {
perror("shmat");
exit(1);
}
// Parent process writes to shared memory
*shared_memory = 42;
// Fork a child process
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
// Child process reads from shared memory
std::cout << "Child Process: Value read from shared memory: " << *shared_memory << std::endl;
exit(0);
} else {
// Parent process waits for child to finish
wait(NULL);
// Detach from the shared memory segment
if (shmdt(shared_memory) == -1) {
perror("shmdt");
exit(1);
}
// Remove the shared memory segment (optional)
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}
}
return 0;
}
Editor is loading...
Leave a Comment