Develop a program that creates a shared memory segment and reads contents from a
ID: 3660162 • Letter: D
Question
Develop a program that creates a shared memory segment and reads contents from a file to the shared memory segment. Develop the other program that reads from the shared memory segment and outputs what it reads. After running the two programs successfully, practice change ownership of the shared memory segment. Note that you prepare a plain text file for testing.Explanation / Answer
#include #include #include #include #include #include #define SHM_SIZE 1024 /* make it a 1K shared memory segment */ int main(int argc, char *argv[]) { key_t key; int shmid; char *data; int mode; if (argc > 2) { fprintf(stderr, "usage: shmdemo [data_to_write] "); exit(1); } /* make the key: */ if ((key = ftok("shmdemo.c", 'R')) == -1) { perror("ftok"); exit(1); } /* connect to (and possibly create) the segment: */ if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) { perror("shmget"); exit(1); } /* attach to the segment to get a pointer to it: */ data = shmat(shmid, (void *)0, 0); if (data == (char *)(-1)) { perror("shmat"); exit(1); } /* read or modify the segment, based on the command line: */ if (argc == 2) { printf("writing to segment: "%s" ", argv[1]); strncpy(data, argv[1], SHM_SIZE); } else printf("segment contains: "%s" ", data); /* detach from the segment: */ if (shmdt(data) == -1) { perror("shmdt"); exit(1); } return 0; }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.