SlideShare a Scribd company logo
NarayanLal Menariya August30,2018
Synchronization of shared memory using Semaphore
Using semaphores synchronization can beprovided between two or moreprocess. Here
i am going to writea codewhich will clear that how a semaphorecan be used with
shared memory to providesynchronization between writing processand reading
process.
The following codewrites structurein shared memory and read it back. Oncethe writing
process will writefirst messageinto shared memory receiver process will read it
immediately and will wait for second messageto arriveinto shared memory. Receiver
process will be in sleep statetill thenew data will arrivein shared memory. Just like
producer-consumer problem.
This code is written by meonly and not copied from anywhere.
Code : writeIn_sharedMemory_UsingSemaphore.c
1. /*
2. Narayan Lal Menariya:August30,2018
3. * */
4. #include<sys/sem.h>
5. #include<stdio.h>
6. #include<sys/shm.h>
7. #include<sys/ipc.h>
8. #include<string.h>
9. #include "file.h"
10.
11. int counter;
12.
13.
14. struct student
15. {
16. intid;
17. char name[20];
18. }stdobj;
19.
20. int main()
21. {
22. intret;
23. char choice;
24. char msg[20];
25. struct student*ptr;
26.
27. //declaringkeyforsemaphore
28. key_tsemKey =1;
29. //creatingkeyforsharedmemory
30. key_tshmKey =100;
31.
32. //requestingkernel toreturnsemaphore memoryid
33. intsemid = semget(semKey,1,IPC_CREAT|0666);//semkey,no.of sem, flg|permission
34.
35. if(semid==-1)
36. perror("semget");
37. else
38. {
39. //ACQUIRINGSEMAPHORE:semval =1 meanssemaphore isavailable
40. ret = semctl(semid,0, SETVAL, 1);//semid,semaphore number,setvalue =1
41. if(ret== -1)
42. perror("smctl");
43. else
44. {
45. //creatingsemaphore structure
46. struct sembuf x = {0,-1,0}; //semaphore number,decrementoperation,
IPC_NOWAIT:processshouldrelease semexplicitly
47.
48. //performlockingoperationon
49. ret= semop(semid,&x,1);
50. if(ret== -1) perror("semop");
51. else {
printf("semaphorelocked n");
52.
53. //requestingkernel toallocate sharedmemoryandreturnshmid
54. intshmid= shmget(shmKey,sizeof(stdobj), IPC_CREAT|0666);
55.
56. //attachingtosharedmemory
57. ptr = (struct student*)shmat(shmid,NULL,0);
58.
59. if(ptr)
60. {
61. printf("Attachedsuccessfullyn");
62. printf("Doyouwantto write insharedmemory1. y:yes,2.n:non");
63. while(1)
64. {
65. scanf("%c",&choice);
66. if(choice =='y')
67. {
68. //ptr = &stdobj;
69. printf("enterstudentid:n");
70. scanf("%d",&stdobj.id);
71. printf("enterstudentname :n");
72. scanf("%s",&stdobj.name);
73.
74. printf("name :%sn",stdobj.name);
75. printf("id:%dn",stdobj.id);
76.
77. (*ptr).id= stdobj.id;
78. strcpy((*ptr).name,stdobj.name);
79.
80.
81. printf("nDatawrittensuccessfullyn");
82. ptr++;
83. printf("writechoice y/n:");
84. }
85. if(choice =='n')
86. {
87.
88. break;
89. }
90.
91. }
92.
93. //deattachingfrommemory
94. shmdt(ptr);
95. printf("deattachedsuccessfullyn");
96. //releasingsemaphore
97. semctl(semid,0,SETVAL,1);
98.
99. }
100. else
101. perror("shmat");
102. }
103. }
104. }
105. return 0;
106. }
Code :Read_UsingSemaphore.c
1. /*
2. Narayan Lal Menariya:August30,2018
3. * */
4. #include<sys/sem.h>
5. #include<stdio.h>
6. #include<sys/shm.h>
7. #include<sys/ipc.h>
8. #include<string.h>
9.
10.
11. struct student
12. {
13. intid;
14. char name[20];
15. }stdobj;
16.
17. int main()
18. {
19. intret;
20. char choice;
21. char msg[20];
22. struct student*ptr;
23.
24. //declaringkeyforsemaphore
25. key_tsemKey =1;
26. //creatingkeyforsharedmemory
27. key_tshmKey =100;
28.
29. //requestingkernel to returnsemaphore memoryid
30. intsemid = semget(semKey,1,IPC_CREAT|0666);//semkey,no.of sem, flg|permission
31.
32. if(semid==-1)
33. perror("semget");
34. else
35. {
36. struct sembuf x = {0,-1,0}; //semaphore number,decrementoperation,IPC_NOWAIT
37. //performlockingoperationon
38. ret= semop(semid,&x,1);
39. if(ret== -1) perror("semop");
40. else {
printf("semaphorelocked n");
41.
42. //requestingkernel toallocate sharedmemoryandreturnshmid
43. intshmid= shmget(shmKey,sizeof(stdobj), IPC_CREAT|0666);
44.
45. //attachingtosharedmemory
46. ptr = (struct student*)shmat(shmid,NULL,0);
47.
48. if(ptr)
49. {
50. printf("Attachedsuccessfullyn");
51. while(1)
52. {
53. while((*ptr).id!=0)
54. {
55.
56. printf("studentid:%dn",(*ptr).id);
57. printf("studentname :%sn",(*ptr).name);
58.
59. printf("Datareadsuccessfullyn");
60. ptr++;
61. }
62. }
63. //deattachingfrommemory
64. shmdt(ptr);
65. printf("deattachedsuccessfullyn");
66. //release explicitly
67. semctl(semid,0,SETVAL,1);
68. }
69. else
70. perror("shmat");
71. }
72. }
73. return 0;
74. }
If you haveany doubt than feel free to ask.
Thanks.

More Related Content

What's hot

wireless network IEEE 802.11
 wireless network IEEE 802.11 wireless network IEEE 802.11
wireless network IEEE 802.11
Shreejan Acharya
 
REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transferTricode (part of Dept)
 
Android architecture
Android architectureAndroid architecture
Android architecture
poojapainter
 
8. internal components of router
8. internal components of router8. internal components of router
8. internal components of routerSwarndeep Singh
 
Introduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationIntroduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationKelwin Yang
 
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLSBASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
amiteshg
 
Mac protocols sensor_20071105_slideshare
Mac protocols sensor_20071105_slideshareMac protocols sensor_20071105_slideshare
Mac protocols sensor_20071105_slideshare
Chih-Yu Lin
 
Android 10
Android 10Android 10
Android and android versions
Android and android versionsAndroid and android versions
Android and android versions
Megha Jain
 
Unit 1 - mobile computing introduction
Unit 1 - mobile computing introductionUnit 1 - mobile computing introduction
Unit 1 - mobile computing introduction
Vintesh Patel
 
Symbian Operating system
Symbian Operating systemSymbian Operating system
Symbian Operating system
Pravin Shinde
 
Software Defined Network - SDN
Software Defined Network - SDNSoftware Defined Network - SDN
Software Defined Network - SDN
Venkata Naga Ravi
 
Gsm security algorithms A3 , A5 , A8
Gsm security algorithms A3 , A5 , A8Gsm security algorithms A3 , A5 , A8
Gsm security algorithms A3 , A5 , A8
RUpaliLohar
 
Symbian Os Introduction
Symbian Os IntroductionSymbian Os Introduction
Symbian Os Introduction
Deepak Rathi
 
6lowpan
6lowpan6lowpan
IT8602 Mobile Communication - Unit III
IT8602 Mobile Communication  - Unit IIIIT8602 Mobile Communication  - Unit III
IT8602 Mobile Communication - Unit III
pkaviya
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
Pietro Alberto Rossi
 
IEEE 802.11 Architecture and Services
IEEE 802.11 Architecture and ServicesIEEE 802.11 Architecture and Services
IEEE 802.11 Architecture and Services
Sayed Chhattan Shah
 

What's hot (20)

wireless network IEEE 802.11
 wireless network IEEE 802.11 wireless network IEEE 802.11
wireless network IEEE 802.11
 
REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transfer
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
8. internal components of router
8. internal components of router8. internal components of router
8. internal components of router
 
Introduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android ApplicationIntroduction to Dynamic Analysis of Android Application
Introduction to Dynamic Analysis of Android Application
 
Osi model
Osi modelOsi model
Osi model
 
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLSBASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
BASIC OF ROUTERS,ROUTER IOS AND ROUTING PROTOCOLS
 
Mac protocols sensor_20071105_slideshare
Mac protocols sensor_20071105_slideshareMac protocols sensor_20071105_slideshare
Mac protocols sensor_20071105_slideshare
 
Android 10
Android 10Android 10
Android 10
 
Android and android versions
Android and android versionsAndroid and android versions
Android and android versions
 
Unit 1 - mobile computing introduction
Unit 1 - mobile computing introductionUnit 1 - mobile computing introduction
Unit 1 - mobile computing introduction
 
Symbian Operating system
Symbian Operating systemSymbian Operating system
Symbian Operating system
 
Software Defined Network - SDN
Software Defined Network - SDNSoftware Defined Network - SDN
Software Defined Network - SDN
 
Gsm security algorithms A3 , A5 , A8
Gsm security algorithms A3 , A5 , A8Gsm security algorithms A3 , A5 , A8
Gsm security algorithms A3 , A5 , A8
 
Symbian Os Introduction
Symbian Os IntroductionSymbian Os Introduction
Symbian Os Introduction
 
6lowpan
6lowpan6lowpan
6lowpan
 
WebSphere MQ introduction
WebSphere MQ introductionWebSphere MQ introduction
WebSphere MQ introduction
 
IT8602 Mobile Communication - Unit III
IT8602 Mobile Communication  - Unit IIIIT8602 Mobile Communication  - Unit III
IT8602 Mobile Communication - Unit III
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
 
IEEE 802.11 Architecture and Services
IEEE 802.11 Architecture and ServicesIEEE 802.11 Architecture and Services
IEEE 802.11 Architecture and Services
 

Similar to Synchronization of shared memory using semaphores

Message queue and shared memory
Message queue and shared memoryMessage queue and shared memory
Message queue and shared memory
NarayanlalMenariya
 
IRJET- Login System for Web: Session Management using BCRYPTJS
IRJET- Login System for Web: Session Management using BCRYPTJSIRJET- Login System for Web: Session Management using BCRYPTJS
IRJET- Login System for Web: Session Management using BCRYPTJS
IRJET Journal
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
wkyra78
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJS
Thang Chung
 
IPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared MemoryIPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared Memory
HEM DUTT
 
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
Matt Raible
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
PVS-Studio
 
A simple html login page using java s
A simple html login page using java sA simple html login page using java s
A simple html login page using java s
Joel Bisonzi
 
Honey words
Honey wordsHoney words
Honey words
Sreya Sridhar PP
 
Linux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLiteLinux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLite
PVS-Studio
 
IRJET- Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
IRJET-  	  Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud StorageIRJET-  	  Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
IRJET- Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
IRJET Journal
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JSFestUA
 
KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
 KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ... KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
Nexgen Technology
 
How Your DRAM Becomes a Security Problem
How Your DRAM Becomes a Security ProblemHow Your DRAM Becomes a Security Problem
How Your DRAM Becomes a Security Problem
mark-smith
 
Project Jugaad
Project JugaadProject Jugaad
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
IRJET Journal
 
OSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionOSTEP Chapter2 Introduction
OSTEP Chapter2 Introduction
Shuya Osaki
 

Similar to Synchronization of shared memory using semaphores (20)

Message queue and shared memory
Message queue and shared memoryMessage queue and shared memory
Message queue and shared memory
 
Lab8
Lab8Lab8
Lab8
 
IRJET- Login System for Web: Session Management using BCRYPTJS
IRJET- Login System for Web: Session Management using BCRYPTJSIRJET- Login System for Web: Session Management using BCRYPTJS
IRJET- Login System for Web: Session Management using BCRYPTJS
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJS
 
IPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared MemoryIPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared Memory
 
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
 
Introduction to Greasemonkey
Introduction to GreasemonkeyIntroduction to Greasemonkey
Introduction to Greasemonkey
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
 
A simple html login page using java s
A simple html login page using java sA simple html login page using java s
A simple html login page using java s
 
Honey words
Honey wordsHoney words
Honey words
 
Linux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLiteLinux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLite
 
IRJET- Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
IRJET-  	  Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud StorageIRJET-  	  Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
IRJET- Key-Aggregate Cryptosystem for Scalable Data Sharing in Cloud Storage
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
 
KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
 KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ... KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
KEY-AGGREGATE SEARCHABLE ENCRYPTION (KASE) FOR GROUP DATA SHARING VIA CLOUD ...
 
How Your DRAM Becomes a Security Problem
How Your DRAM Becomes a Security ProblemHow Your DRAM Becomes a Security Problem
How Your DRAM Becomes a Security Problem
 
Project Jugaad
Project JugaadProject Jugaad
Project Jugaad
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
IRJET- Cancelable Biometric based Key Generation for Symmetric Cryptography: ...
 
OSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionOSTEP Chapter2 Introduction
OSTEP Chapter2 Introduction
 

More from NarayanlalMenariya

Updated CV
Updated CVUpdated CV
Updated CV
NarayanlalMenariya
 
Curriculum Vitae
Curriculum VitaeCurriculum Vitae
Curriculum Vitae
NarayanlalMenariya
 
Face Detection And Tracking
Face Detection And TrackingFace Detection And Tracking
Face Detection And Tracking
NarayanlalMenariya
 
Resume for fresher
Resume for fresherResume for fresher
Resume for fresher
NarayanlalMenariya
 
C++ Programs
C++ ProgramsC++ Programs
C++ Programs
NarayanlalMenariya
 
Character recognition
Character recognitionCharacter recognition
Character recognition
NarayanlalMenariya
 
GUI based calculator using MATLAB
GUI based calculator using MATLABGUI based calculator using MATLAB
GUI based calculator using MATLAB
NarayanlalMenariya
 
Steganography
SteganographySteganography
Steganography
NarayanlalMenariya
 
client-server communication using socket IPC
client-server communication using socket IPCclient-server communication using socket IPC
client-server communication using socket IPC
NarayanlalMenariya
 
Home automation using MATLAB image processing
Home automation using MATLAB image processingHome automation using MATLAB image processing
Home automation using MATLAB image processing
NarayanlalMenariya
 
Simplified Experimental Determination of Line Transient Immunity of Linear Re...
Simplified Experimental Determination of Line Transient Immunity of Linear Re...Simplified Experimental Determination of Line Transient Immunity of Linear Re...
Simplified Experimental Determination of Line Transient Immunity of Linear Re...
NarayanlalMenariya
 
SMART E-TOLL SYSTEM
SMART E-TOLL SYSTEMSMART E-TOLL SYSTEM
SMART E-TOLL SYSTEM
NarayanlalMenariya
 
Voice From Deep Of Heart
Voice From Deep Of HeartVoice From Deep Of Heart
Voice From Deep Of Heart
NarayanlalMenariya
 
Lidar and sensing
Lidar and sensingLidar and sensing
Lidar and sensing
NarayanlalMenariya
 
A chip to protect IOT
A chip to protect IOTA chip to protect IOT
A chip to protect IOT
NarayanlalMenariya
 

More from NarayanlalMenariya (15)

Updated CV
Updated CVUpdated CV
Updated CV
 
Curriculum Vitae
Curriculum VitaeCurriculum Vitae
Curriculum Vitae
 
Face Detection And Tracking
Face Detection And TrackingFace Detection And Tracking
Face Detection And Tracking
 
Resume for fresher
Resume for fresherResume for fresher
Resume for fresher
 
C++ Programs
C++ ProgramsC++ Programs
C++ Programs
 
Character recognition
Character recognitionCharacter recognition
Character recognition
 
GUI based calculator using MATLAB
GUI based calculator using MATLABGUI based calculator using MATLAB
GUI based calculator using MATLAB
 
Steganography
SteganographySteganography
Steganography
 
client-server communication using socket IPC
client-server communication using socket IPCclient-server communication using socket IPC
client-server communication using socket IPC
 
Home automation using MATLAB image processing
Home automation using MATLAB image processingHome automation using MATLAB image processing
Home automation using MATLAB image processing
 
Simplified Experimental Determination of Line Transient Immunity of Linear Re...
Simplified Experimental Determination of Line Transient Immunity of Linear Re...Simplified Experimental Determination of Line Transient Immunity of Linear Re...
Simplified Experimental Determination of Line Transient Immunity of Linear Re...
 
SMART E-TOLL SYSTEM
SMART E-TOLL SYSTEMSMART E-TOLL SYSTEM
SMART E-TOLL SYSTEM
 
Voice From Deep Of Heart
Voice From Deep Of HeartVoice From Deep Of Heart
Voice From Deep Of Heart
 
Lidar and sensing
Lidar and sensingLidar and sensing
Lidar and sensing
 
A chip to protect IOT
A chip to protect IOTA chip to protect IOT
A chip to protect IOT
 

Recently uploaded

一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 

Recently uploaded (20)

一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 

Synchronization of shared memory using semaphores

  • 1. NarayanLal Menariya August30,2018 Synchronization of shared memory using Semaphore Using semaphores synchronization can beprovided between two or moreprocess. Here i am going to writea codewhich will clear that how a semaphorecan be used with shared memory to providesynchronization between writing processand reading process. The following codewrites structurein shared memory and read it back. Oncethe writing process will writefirst messageinto shared memory receiver process will read it immediately and will wait for second messageto arriveinto shared memory. Receiver process will be in sleep statetill thenew data will arrivein shared memory. Just like producer-consumer problem. This code is written by meonly and not copied from anywhere. Code : writeIn_sharedMemory_UsingSemaphore.c 1. /* 2. Narayan Lal Menariya:August30,2018 3. * */ 4. #include<sys/sem.h> 5. #include<stdio.h> 6. #include<sys/shm.h> 7. #include<sys/ipc.h> 8. #include<string.h> 9. #include "file.h" 10. 11. int counter; 12. 13. 14. struct student 15. { 16. intid; 17. char name[20]; 18. }stdobj; 19. 20. int main() 21. { 22. intret; 23. char choice; 24. char msg[20]; 25. struct student*ptr; 26. 27. //declaringkeyforsemaphore 28. key_tsemKey =1; 29. //creatingkeyforsharedmemory 30. key_tshmKey =100;
  • 2. 31. 32. //requestingkernel toreturnsemaphore memoryid 33. intsemid = semget(semKey,1,IPC_CREAT|0666);//semkey,no.of sem, flg|permission 34. 35. if(semid==-1) 36. perror("semget"); 37. else 38. { 39. //ACQUIRINGSEMAPHORE:semval =1 meanssemaphore isavailable 40. ret = semctl(semid,0, SETVAL, 1);//semid,semaphore number,setvalue =1 41. if(ret== -1) 42. perror("smctl"); 43. else 44. { 45. //creatingsemaphore structure 46. struct sembuf x = {0,-1,0}; //semaphore number,decrementoperation, IPC_NOWAIT:processshouldrelease semexplicitly 47. 48. //performlockingoperationon 49. ret= semop(semid,&x,1); 50. if(ret== -1) perror("semop"); 51. else { printf("semaphorelocked n"); 52. 53. //requestingkernel toallocate sharedmemoryandreturnshmid 54. intshmid= shmget(shmKey,sizeof(stdobj), IPC_CREAT|0666); 55. 56. //attachingtosharedmemory 57. ptr = (struct student*)shmat(shmid,NULL,0); 58. 59. if(ptr) 60. { 61. printf("Attachedsuccessfullyn"); 62. printf("Doyouwantto write insharedmemory1. y:yes,2.n:non"); 63. while(1) 64. { 65. scanf("%c",&choice); 66. if(choice =='y') 67. { 68. //ptr = &stdobj; 69. printf("enterstudentid:n"); 70. scanf("%d",&stdobj.id); 71. printf("enterstudentname :n"); 72. scanf("%s",&stdobj.name); 73. 74. printf("name :%sn",stdobj.name); 75. printf("id:%dn",stdobj.id); 76. 77. (*ptr).id= stdobj.id; 78. strcpy((*ptr).name,stdobj.name); 79.
  • 3. 80. 81. printf("nDatawrittensuccessfullyn"); 82. ptr++; 83. printf("writechoice y/n:"); 84. } 85. if(choice =='n') 86. { 87. 88. break; 89. } 90. 91. } 92. 93. //deattachingfrommemory 94. shmdt(ptr); 95. printf("deattachedsuccessfullyn"); 96. //releasingsemaphore 97. semctl(semid,0,SETVAL,1); 98. 99. } 100. else 101. perror("shmat"); 102. } 103. } 104. } 105. return 0; 106. } Code :Read_UsingSemaphore.c 1. /* 2. Narayan Lal Menariya:August30,2018 3. * */ 4. #include<sys/sem.h> 5. #include<stdio.h> 6. #include<sys/shm.h> 7. #include<sys/ipc.h> 8. #include<string.h> 9. 10. 11. struct student 12. { 13. intid; 14. char name[20]; 15. }stdobj; 16. 17. int main() 18. { 19. intret; 20. char choice; 21. char msg[20]; 22. struct student*ptr;
  • 4. 23. 24. //declaringkeyforsemaphore 25. key_tsemKey =1; 26. //creatingkeyforsharedmemory 27. key_tshmKey =100; 28. 29. //requestingkernel to returnsemaphore memoryid 30. intsemid = semget(semKey,1,IPC_CREAT|0666);//semkey,no.of sem, flg|permission 31. 32. if(semid==-1) 33. perror("semget"); 34. else 35. { 36. struct sembuf x = {0,-1,0}; //semaphore number,decrementoperation,IPC_NOWAIT 37. //performlockingoperationon 38. ret= semop(semid,&x,1); 39. if(ret== -1) perror("semop"); 40. else { printf("semaphorelocked n"); 41. 42. //requestingkernel toallocate sharedmemoryandreturnshmid 43. intshmid= shmget(shmKey,sizeof(stdobj), IPC_CREAT|0666); 44. 45. //attachingtosharedmemory 46. ptr = (struct student*)shmat(shmid,NULL,0); 47. 48. if(ptr) 49. { 50. printf("Attachedsuccessfullyn"); 51. while(1) 52. { 53. while((*ptr).id!=0) 54. { 55. 56. printf("studentid:%dn",(*ptr).id); 57. printf("studentname :%sn",(*ptr).name); 58. 59. printf("Datareadsuccessfullyn"); 60. ptr++; 61. } 62. } 63. //deattachingfrommemory 64. shmdt(ptr); 65. printf("deattachedsuccessfullyn"); 66. //release explicitly 67. semctl(semid,0,SETVAL,1); 68. } 69. else 70. perror("shmat"); 71. } 72. }
  • 5. 73. return 0; 74. } If you haveany doubt than feel free to ask. Thanks.