[AcuñaQ10] Consider the following program that creates shared memory and writes
ID: 3736935 • Letter: #
Question
[AcuñaQ10] Consider the following program that creates shared memory and writes the phrase “HelloWorld!” to it.
void main() { //code sample from Operating System Concepts, page 132 of Chapter 3 in 9th edition.
const int SIZE = 4096;
const char *name = "OS"; //LINE A
const char *message_0 = "Hello";
const char *message_1 = "World!";
int shm_fd;
void *ptr;
shm_fd = shm_open(name, O_CREAT | O_RDRW, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
sprintf(ptr, "%s", message_0);
ptr += strlen(message_0); //LINE B
sprintf(ptr, "%s", message_1);
ptr += strlen(message_1);
}
(a) [Acuña] Explain why the variable name on LINE A is set to “OS”. What would be the change in program behavior if it changed? [1 point]
(b) [Acuña] Explain the change in program behavior if LINE B was commented out. [1 point]
Explanation / Answer
a) There are three arguments in shm_open() API.
#include <sys/mman.h>
int shm_open(const char *name, int oflag, mode_t mode);
name=First argument is to provide a name for the shared memory;
oflag=second argument tells about the access mode (read/write);
mode=third argument is a flag for permission bit setting
You can change the variable name="OS" to any other name. Just make sure it is a valid string, such as
char* name="my_shared_momory"; this name change will not change the program behavior.
b)
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); //ptr will hold the starting address of shared memory
sprintf(ptr, "%s", message_0); //message_0("Hello") will print at first address of shared memory
ptr += strlen(message_0); //LINE B //this line will shift the pointer to the address of shared memory after the word "Hello"
sprintf(ptr, "%s", message_1); //now message_1("World!") will print after "Hello"
ptr += strlen(message_1); //pointer is again shifting after "World!".
If you comment LINE B "Hello" will be overridden by "World!" because you have not shifted your pointer after "Hello" and writen "World!" in place of "Hello". So when you read shared memory you will get "World!" only.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.