logo

Shared Memory Segment Creation and Destruction in C Programming

   

Added on  2023-06-03

29 Pages2258 Words453 Views
1Running Head: OPERATING SYSTEM
Operating System
Institution
Date
Name

2OPERATING SYSTEM
To create a Shared memory segment we have to use shmget() function. The
prototype of this function is:
int shmget(key_t,size,flag);
To create a segment we need to pass a key, the size of segment and a flag to
specify what way the segment will be used. If flag is IPC_CREAT , it means it is for
server and 0666 for client.
So in the program we use shmget(key,32,IPC_CREAT) and it returns an ID of
type int integer after sucessfully creation of segment.
And to destroy the segment, we use shmctl() function. The prototype of the
function is:
shmctl(shmid,IPC_RMID,NULL);
So this function takes the shared memory ID(the ID that was returned by
shmget() function), and IPC_RMID flag to indicate to remove the ID and NULL.
Here is the program:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
int main()
{
key_t key = 1256482; // You can use any key value

3OPERATING SYSTEM
printf("-Using key %d\n",key); // Printing the used key to create shared memory
segment int shmid = shmget(key,32,IPC_CREAT); // we are creating the shared
memory segment using key
printf("-Shared memory segment created with ID %d\n",shmid); // Printing the
ID of shared memory segment
printf("-Sleeping for 10 seconds...\n");
sleep(10); // Sleeping for 10 seconds
shmctl(shmid,IPC_RMID,NULL); // destroying the shared memory segment
using the ID of segment
Printf ("-Shared memory segment destroyed\n");
return 0;
}
Output
1) Initially the status of shared memory segments was as in this screenshot:

4OPERATING SYSTEM

5OPERATING SYSTEM
2) Then at the time of execution this is the scenario:
See the ID created at the time of execution(RIGHT TERMINAL) and the last
row of LEFT TERMINAL, they are same.
3) Now after the termination of the program The segment is destroyed.

6OPERATING SYSTEM
Task 2:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>

End of preview

Want to access all the pages? Upload your documents or become a member.

Related Documents
Operating System
|30
|2055
|230

Inter-process Communication and Synchronisation
|11
|2268
|343

COMP9812 - Computer Networks And Operating Systems
|34
|3084
|208

Shared Memory and Inter-Process Communication in Operating Systems
|34
|3181
|51