memory region, with the child process writing a value to the shared memory and the parent process reading that value. This is my code and I wont run. Can you help: #include #include #include #include #include #include
Description:
The project I am working on needs to demonstrate how two processes (parent and child) can communicate
through a shared memory region, with the child process writing a value to the shared memory
and the parent process reading that value.
This is my code and I wont run. Can you help:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#define SHM_SIZE 1024 /* shared memory size */
void error_exit(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main() {
key_t key;
int shmid;
char *data;
// Create a unique key for shared memory
if ((key = ftok("shared_memory.c", 'R')) == -1) {
error_exit("ftok");
}
// Create the shared memory segment
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
error_exit("shmget");
}
// Attach the shared memory segment to our data space
data = shmat(shmid, (void *)0, 0);
if (data == (char *)(-1)) {
error_exit("shmat");
}
// Fork a child process
pid_t pid = fork();
if (pid < 0) {
error_exit("fork");
}
else if (pid == 0) { // Child process
*data = 0xDEADBEEF; // Write to shared memory
}
else { // Parent process
wait(NULL); // Wait for the child to finish
// Read from the shared memory
if (*data == 0xDEADBEEF) {
printf("The child wrote 0xDEADBEEF\n");
}
}
// Detach from the shared memory
if (shmdt(data) == -1) {
error_exit("shmdt");
}
// Clean up shared memory
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
error_exit("shmctl");
}
return 0;
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps