SlideShare a Scribd company logo
1 of 8
Narayan Lal Menariya August 30,2018
Message queue and shared memory
Messagequeueand shared memory both areused to achieve interprocess
communication(IPC). Useof messagequeueand shared memory both havethere own
advantages as well as disadvantages. Let first havea brief description about message
queue and shared memory later i will sharemy own written codewith you.
1. Message Queue:By default messagequeueallows FIFO order of accessing
data/messages from messagequeue. But process can read any messageby
defining message_type whilecalling msgrcv() system call.
a. Messagequeueis kernel persistence: It means messagequeuewill remain
aliveunless and until you will not deleteit explicitly or will not shutdown the
system and restart it back.
b. messagequeues are stored in kernel space.
c. messagequeueis not broad casting.
d. system call overheads aremorein messagequeue.
2. Shared Memory: Shared memory get placein heap memory(user space) thus
system call overheads arevery less.
a. Destructivereading is not therein shared memory but it is present in caseof
messagequeue.
b. Shared memory is faster than messagequeue.
c. Shared memory is broad casting so semaphoresareused for synchronization.
Code for Message queue: In this codeoneprocess writes completestructurein message
queue whileother process read that structure. A student structureis created which
receives student Id and Student Namefrom user and writes into messagequeueon
desired message_type. message_type should beinteger value. At thereceiver end side
user need to input message_type, onceuser will enter it data present on this location
will be fetched and will present in front of you.
This code is completely error freeand implemented by meown. I have not copied it
from anywhere.
Program to writein messagequeue: WriteIn_messageQueue.c
1. /*
2.
3. NarayanLal Menariya:August28,2018
4.
5. * */
6.
7. #include<sys/types.h>
8. #include<sys/ipc.h>
9. #include<sys/msg.h>
10. #include<string.h>
11. #include<stdio.h>
12. //creatingstructure message queue:todefinetype of message andmessage data
13. struct myMessage
14. {
15. longmess_type;
16.
17. struct StdDetail
18. {
19. int Id;
20. char Name[20];
21. }stdobj;
22. };
23.
24. int main()
25. {
26. key_tkey = 8;
27.
28. //requestingfromkernel toallocate message queue inkernel space andgive messagequeueid
29.
30. intmy_id= msgget(key,IPC_CREAT|0666);
31. if(my_id==-1)
32. perror("msgget");
33. else
34. {
35. printf("Message queue createdsuccessfullyn");
36. printf("myid:%dn",my_id);
37. }
38.
39. struct myMessage msg;//creatingobjectformessage queue structure
40.
41. char choice;
42. printf("Doyouwanttoinsertdata inmessage queue 1.y:Yes, 2. n : Non");
43. while(1)
44. {
45. scanf("%c",&choice);
46.
47. if(choice == 'y')
48. {
49. printf("entermessage type(kindlyenterintvale) :");
50. scanf("%d",&msg.mess_type);
51. printf("Enterstudentid:");
52. scanf("%d",&msg.stdobj.Id);
53. printf("nEnterstudentname :");
54. scanf("%s",&msg.stdobj.Name);
55.
56. //printf("id:%d",msg.stdobj.Id);
57. //printf("%s",msg.stdobj.Name);
58. intret = msgsnd(my_id,&msg,sizeof(msg.stdobj), IPC_NOWAIT); //sending message
59.
60. if(ret== -1)
61. perror("msgsnd");
62. else
63. {
64. printf("message writtensuccessfullyn");
65. printf("Enterchoice y/n:n");
66. }
67.
68.
69. }
70. if(choice == 'n')
71. {
72. break;
73. }
74. }
75.
76. return 0;
77. }
Program to read messages from queue: ReadFrom_messageQueue.c
1. /*
2.
3. NarayanLal Menariya:August28,2018
4.
5. * */
6.
7. #include<sys/types.h>
8. #include<sys/ipc.h>
9. #include<sys/msg.h>
10. #include<string.h>
11. #include<stdio.h>
12. //creatingstructure message queue:todefinetype of message andmessage data
13.
14. struct myMessage
15. {
16. longmess_type;
17.
18. struct StdDetail
19. {
20. int Id;
21. char Name[20];
22. }stdobj;
23. };
24.
25.
26.
27. int main()
28. {
29. key_tkey = 8;
30. struct myMessage msg;//creatingobjectformessage queue structure
31.
32. //requestingfromkernel togive message queue id
33. intmy_id= msgget(key,IPC_CREAT|0666);
34. if(my_id==-1)
35. perror("");
36. else
37. {
38. char choice;
39. printf("Doyouwanttoread messages1.y:yes,2. n: Non");
40. while(1)
41. {
42.
43. scanf("%c",&choice);
44.
45. if(choice == 'y')
46. {
47. printf("myid:%dn",my_id);
48. printf("Entervalidmessagetype :");
49. scanf("%d",&msg.mess_type);
50.
51. //readingmessage
52. ssize_tret= msgrcv(my_id,&msg, sizeof(msg.stdobj),msg.mess_type,IPC_NOWAIT);
53.
54. if(ret< 0)
55. perror("msgrcv");
56. else
57. {
58. printf("studentId:%dn",msg.stdobj.Id);
59. printf("studentName :%sn",msg.stdobj.Name);
60. printf("Enterchoice y/n:");
61. }
62.
63.
64. }
65. if(choice == 'n')
66. break;
67. }
68. }
69.
70. return 0;
71. }
Code for Shared memory: The following codealso writes structurein shared memory
and read it back. Once the 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 bein sleep statetill thedata will arrivein shared
memory. Just likeproducer-consumer problem.
This code is also written by meonly and not copied from anywhere.
code : writeIn_sharedMemory.c
1. /*
2. Narayan Lal Menariya:August28,2018
3. * */
4.
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. counter=0;
23. //creatingkeyforsharedmemory
24. key_tshmKey =100;
25. char choice;
26. char msg[20];
27.
28. struct student*ptr;
29.
30. //requestingkernel toallocate sharedmemoryandreturnshmid
31. intshmid = shmget(shmKey,sizeof(stdobj),IPC_CREAT|0666);//key,size, flg|permission
32.
33. //attachingtosharedmemory
34. ptr = (struct student*)shmat(shmid,NULL,0);//id,address,flg,0: read-write operation
35.
36. if(ptr> 0)
37. {
38. printf("Attachedsuccessfullyn");
39. printf("Doyouwantto write insharedmemory1.y:yes,2. n:non");
40. while(1)
41. {
42. scanf("%c",&choice);
43. if(choice =='y')
44. {
45. //ptr = &stdobj;
46. printf("enterstudentid:n");
47. scanf("%d",&stdobj.id);
48. printf("enterstudentname :n");
49. scanf("%s",&stdobj.name);
50.
51. printf("name :%sn",stdobj.name);
52. printf("id:%dn",stdobj.id);
53.
54. (*ptr).id= stdobj.id;
55. strcpy((*ptr).name,stdobj.name);
56.
57. //printf("Name :%s",(*ptr).name);
58.
59. printf("nDatawrittensuccessfullyn");
60. ptr++;
61.
62.
63. increment();
64. // counter++;
65. printf("writechoice y/n:");
66. }
67. if(choice =='n')
68. {
69. (*ptr).id= 1;
70. strcpy(stdobj.name,"null");
71. strcpy((*ptr).name,stdobj.name);
72. break;
73. }
74.
75. }
76.
77. //deattachingfrommemory
78. shmdt(ptr);
79. printf("deattachedsuccessfullyn");
80.
81. }
82. else
83. perror("shmat");
84. return 0;
code: readFrom_sharedMemory.c
1. /*
2. Narayan Lal Menariya:August28,2018
3.
4.
5. * */
6.
7. #include<stdio.h>
8. #include<sys/shm.h>
9. #include<sys/ipc.h>
10. #include "file.h"
11. int counter;
12.
13. struct student
14. {
15. intid;
16. char name[20];
17. }stdobj;
18.
19. int main()
20. {
21. printf("counter:%dn",counter);
22. //creatingkeyforsharedmemory
23. key_tshmKey =100;
24.
25. struct student*ptr;
26.
27. //requestingkernel toreturnshemid
28. intshmid = shmget(shmKey,sizeof(stdobj),IPC_CREAT|0666);//key,size,flg|permission
29.
30. //attachingtosharedmemory
31. ptr = (struct student*)shmat(shmid,NULL,0);//id,address,flg,0: read-write operation
32.
33.
34. if(ptr>0)
35. {
36. printf("Attachedsuccessfullyn");
37. // printf("counter:%dn",counter);
38.
39. while(1)
40. {
41. if(((*ptr).id==1) && (strcmp((*ptr).name,"null")==0))
42. break;
43. while((*ptr).id==0)
44. {
45. sleep(1);
46. }
47.
48. while((*ptr).id!=0)
49. {
50.
51. //readingdatafromsharedmemoryat address= ptr
52.
53. if(((*ptr).id==1) && (strcmp((*ptr).name,"null")==0))
54. break;
55.
56. printf("studentid:%dn",(*ptr).id);
57. printf("studentname :%sn",(*ptr).name);
58.
59. printf("Datareadsuccessfullyn");
60. ptr++;
61.
62. //printf("counter:%dn",counter);
63. //counter--;
64. }
65. }
66. //deattachingfrommemory
67. shmdt(ptr);
68. printf("deattachedsuccessfullyn");
69.
70. //removingsharedmemoryid
71. shmctl(shmid,IPC_RMID,0);
72.
73. }
74. else
75. perror("shmat");
76. return 0;
77. }
Happy to help. If you haveany doubt at anywherein codecan ask me.
Thank you.

More Related Content

Similar to Message queue and shared memory

Synchronization of shared memory using semaphores
Synchronization of shared memory using semaphoresSynchronization of shared memory using semaphores
Synchronization of shared memory using semaphoresNarayanlalMenariya
ย 
Inter process communication
Inter process communicationInter process communication
Inter process communicationMohd Tousif
ย 
Virtual Machines Security Internals: Detection and Exploitation
 Virtual Machines Security Internals: Detection and Exploitation Virtual Machines Security Internals: Detection and Exploitation
Virtual Machines Security Internals: Detection and ExploitationMattia Salvi
ย 
data storage security technique for cloud computing
data storage security technique for cloud computingdata storage security technique for cloud computing
data storage security technique for cloud computinghasimshah
ย 
Trap Handling in Linux
Trap Handling in LinuxTrap Handling in Linux
Trap Handling in LinuxYongraeJo
ย 
6. TinyOS_2.pdf
6. TinyOS_2.pdf6. TinyOS_2.pdf
6. TinyOS_2.pdfJesus Cordero
ย 
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...IJCSIS Research Publications
ย 
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...TELKOMNIKA JOURNAL
ย 
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Vincenzo Iozzo
ย 
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...IOSRjournaljce
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
ย 
Write text file in c#
Write text file in c#Write text file in c#
Write text file in c#gridviewnet
ย 
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...IOSR Journals
ย 
A Review Paper on Secure authentication and data sharing in cloud storage usi...
A Review Paper on Secure authentication and data sharing in cloud storage usi...A Review Paper on Secure authentication and data sharing in cloud storage usi...
A Review Paper on Secure authentication and data sharing in cloud storage usi...ijsrd.com
ย 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxSoumen Santra
ย 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.pptaminnezarat
ย 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptxsibokac
ย 

Similar to Message queue and shared memory (20)

Synchronization of shared memory using semaphores
Synchronization of shared memory using semaphoresSynchronization of shared memory using semaphores
Synchronization of shared memory using semaphores
ย 
Project Jugaad
Project JugaadProject Jugaad
Project Jugaad
ย 
Inter process communication
Inter process communicationInter process communication
Inter process communication
ย 
Virtual Machines Security Internals: Detection and Exploitation
 Virtual Machines Security Internals: Detection and Exploitation Virtual Machines Security Internals: Detection and Exploitation
Virtual Machines Security Internals: Detection and Exploitation
ย 
data storage security technique for cloud computing
data storage security technique for cloud computingdata storage security technique for cloud computing
data storage security technique for cloud computing
ย 
Trap Handling in Linux
Trap Handling in LinuxTrap Handling in Linux
Trap Handling in Linux
ย 
6. TinyOS_2.pdf
6. TinyOS_2.pdf6. TinyOS_2.pdf
6. TinyOS_2.pdf
ย 
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...
Caesar Cipher Method Design and Implementation Based on Java, C++, and Python...
ย 
Lab8
Lab8Lab8
Lab8
ย 
Cassandra
CassandraCassandra
Cassandra
ย 
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...
Secure E-voting System by Utilizing Homomorphic Properties of the Encryption ...
ย 
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
Fun and Games with Mac OS X and iPhone Payloads White Paper, Black Hat EU 2009
ย 
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...
Secure Data Sharing and Search in Cloud Based Data Using Authoritywise Dynami...
ย 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
ย 
Write text file in c#
Write text file in c#Write text file in c#
Write text file in c#
ย 
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...
Double Key Encryption Method (DKEM) Algorithms Using ANN for Data Storing and...
ย 
A Review Paper on Secure authentication and data sharing in cloud storage usi...
A Review Paper on Secure authentication and data sharing in cloud storage usi...A Review Paper on Secure authentication and data sharing in cloud storage usi...
A Review Paper on Secure authentication and data sharing in cloud storage usi...
ย 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
ย 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.ppt
ย 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
ย 

More from NarayanlalMenariya

Face Detection And Tracking
Face Detection And TrackingFace Detection And Tracking
Face Detection And TrackingNarayanlalMenariya
ย 
Character recognition
Character recognitionCharacter recognition
Character recognitionNarayanlalMenariya
ย 
GUI based calculator using MATLAB
GUI based calculator using MATLABGUI based calculator using MATLAB
GUI based calculator using MATLABNarayanlalMenariya
ย 
client-server communication using socket IPC
client-server communication using socket IPCclient-server communication using socket IPC
client-server communication using socket IPCNarayanlalMenariya
ย 
Home automation using MATLAB image processing
Home automation using MATLAB image processingHome automation using MATLAB image processing
Home automation using MATLAB image processingNarayanlalMenariya
ย 
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
ย 
Voice From Deep Of Heart
Voice From Deep Of HeartVoice From Deep Of Heart
Voice From Deep Of HeartNarayanlalMenariya
ย 
A chip to protect IOT
A chip to protect IOTA chip to protect IOT
A chip to protect IOTNarayanlalMenariya
ย 

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

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
ย 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
ย 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
ย 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Call Girls in Nagpur High Profile
ย 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .DerechoLaboralIndivi
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
ย 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
ย 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
ย 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
ย 

Recently uploaded (20)

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
ย 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
ย 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ย 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
ย 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
ย 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
ย 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
ย 

Message queue and shared memory

  • 1. Narayan Lal Menariya August 30,2018 Message queue and shared memory Messagequeueand shared memory both areused to achieve interprocess communication(IPC). Useof messagequeueand shared memory both havethere own advantages as well as disadvantages. Let first havea brief description about message queue and shared memory later i will sharemy own written codewith you. 1. Message Queue:By default messagequeueallows FIFO order of accessing data/messages from messagequeue. But process can read any messageby defining message_type whilecalling msgrcv() system call. a. Messagequeueis kernel persistence: It means messagequeuewill remain aliveunless and until you will not deleteit explicitly or will not shutdown the system and restart it back. b. messagequeues are stored in kernel space. c. messagequeueis not broad casting. d. system call overheads aremorein messagequeue. 2. Shared Memory: Shared memory get placein heap memory(user space) thus system call overheads arevery less. a. Destructivereading is not therein shared memory but it is present in caseof messagequeue. b. Shared memory is faster than messagequeue. c. Shared memory is broad casting so semaphoresareused for synchronization. Code for Message queue: In this codeoneprocess writes completestructurein message queue whileother process read that structure. A student structureis created which receives student Id and Student Namefrom user and writes into messagequeueon desired message_type. message_type should beinteger value. At thereceiver end side user need to input message_type, onceuser will enter it data present on this location will be fetched and will present in front of you. This code is completely error freeand implemented by meown. I have not copied it from anywhere. Program to writein messagequeue: WriteIn_messageQueue.c 1. /* 2. 3. NarayanLal Menariya:August28,2018 4. 5. * */ 6. 7. #include<sys/types.h> 8. #include<sys/ipc.h> 9. #include<sys/msg.h> 10. #include<string.h>
  • 2. 11. #include<stdio.h> 12. //creatingstructure message queue:todefinetype of message andmessage data 13. struct myMessage 14. { 15. longmess_type; 16. 17. struct StdDetail 18. { 19. int Id; 20. char Name[20]; 21. }stdobj; 22. }; 23. 24. int main() 25. { 26. key_tkey = 8; 27. 28. //requestingfromkernel toallocate message queue inkernel space andgive messagequeueid 29. 30. intmy_id= msgget(key,IPC_CREAT|0666); 31. if(my_id==-1) 32. perror("msgget"); 33. else 34. { 35. printf("Message queue createdsuccessfullyn"); 36. printf("myid:%dn",my_id); 37. } 38. 39. struct myMessage msg;//creatingobjectformessage queue structure 40. 41. char choice; 42. printf("Doyouwanttoinsertdata inmessage queue 1.y:Yes, 2. n : Non"); 43. while(1) 44. { 45. scanf("%c",&choice); 46. 47. if(choice == 'y') 48. { 49. printf("entermessage type(kindlyenterintvale) :"); 50. scanf("%d",&msg.mess_type); 51. printf("Enterstudentid:"); 52. scanf("%d",&msg.stdobj.Id); 53. printf("nEnterstudentname :"); 54. scanf("%s",&msg.stdobj.Name); 55. 56. //printf("id:%d",msg.stdobj.Id); 57. //printf("%s",msg.stdobj.Name); 58. intret = msgsnd(my_id,&msg,sizeof(msg.stdobj), IPC_NOWAIT); //sending message 59. 60. if(ret== -1) 61. perror("msgsnd");
  • 3. 62. else 63. { 64. printf("message writtensuccessfullyn"); 65. printf("Enterchoice y/n:n"); 66. } 67. 68. 69. } 70. if(choice == 'n') 71. { 72. break; 73. } 74. } 75. 76. return 0; 77. } Program to read messages from queue: ReadFrom_messageQueue.c 1. /* 2. 3. NarayanLal Menariya:August28,2018 4. 5. * */ 6. 7. #include<sys/types.h> 8. #include<sys/ipc.h> 9. #include<sys/msg.h> 10. #include<string.h> 11. #include<stdio.h> 12. //creatingstructure message queue:todefinetype of message andmessage data 13. 14. struct myMessage 15. { 16. longmess_type; 17. 18. struct StdDetail 19. { 20. int Id; 21. char Name[20]; 22. }stdobj; 23. }; 24. 25. 26. 27. int main() 28. { 29. key_tkey = 8; 30. struct myMessage msg;//creatingobjectformessage queue structure 31. 32. //requestingfromkernel togive message queue id 33. intmy_id= msgget(key,IPC_CREAT|0666);
  • 4. 34. if(my_id==-1) 35. perror(""); 36. else 37. { 38. char choice; 39. printf("Doyouwanttoread messages1.y:yes,2. n: Non"); 40. while(1) 41. { 42. 43. scanf("%c",&choice); 44. 45. if(choice == 'y') 46. { 47. printf("myid:%dn",my_id); 48. printf("Entervalidmessagetype :"); 49. scanf("%d",&msg.mess_type); 50. 51. //readingmessage 52. ssize_tret= msgrcv(my_id,&msg, sizeof(msg.stdobj),msg.mess_type,IPC_NOWAIT); 53. 54. if(ret< 0) 55. perror("msgrcv"); 56. else 57. { 58. printf("studentId:%dn",msg.stdobj.Id); 59. printf("studentName :%sn",msg.stdobj.Name); 60. printf("Enterchoice y/n:"); 61. } 62. 63. 64. } 65. if(choice == 'n') 66. break; 67. } 68. } 69. 70. return 0; 71. } Code for Shared memory: The following codealso writes structurein shared memory and read it back. Once the 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 bein sleep statetill thedata will arrivein shared memory. Just likeproducer-consumer problem. This code is also written by meonly and not copied from anywhere. code : writeIn_sharedMemory.c 1. /* 2. Narayan Lal Menariya:August28,2018 3. * */
  • 5. 4. 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. counter=0; 23. //creatingkeyforsharedmemory 24. key_tshmKey =100; 25. char choice; 26. char msg[20]; 27. 28. struct student*ptr; 29. 30. //requestingkernel toallocate sharedmemoryandreturnshmid 31. intshmid = shmget(shmKey,sizeof(stdobj),IPC_CREAT|0666);//key,size, flg|permission 32. 33. //attachingtosharedmemory 34. ptr = (struct student*)shmat(shmid,NULL,0);//id,address,flg,0: read-write operation 35. 36. if(ptr> 0) 37. { 38. printf("Attachedsuccessfullyn"); 39. printf("Doyouwantto write insharedmemory1.y:yes,2. n:non"); 40. while(1) 41. { 42. scanf("%c",&choice); 43. if(choice =='y') 44. { 45. //ptr = &stdobj; 46. printf("enterstudentid:n"); 47. scanf("%d",&stdobj.id); 48. printf("enterstudentname :n"); 49. scanf("%s",&stdobj.name); 50. 51. printf("name :%sn",stdobj.name); 52. printf("id:%dn",stdobj.id); 53. 54. (*ptr).id= stdobj.id;
  • 6. 55. strcpy((*ptr).name,stdobj.name); 56. 57. //printf("Name :%s",(*ptr).name); 58. 59. printf("nDatawrittensuccessfullyn"); 60. ptr++; 61. 62. 63. increment(); 64. // counter++; 65. printf("writechoice y/n:"); 66. } 67. if(choice =='n') 68. { 69. (*ptr).id= 1; 70. strcpy(stdobj.name,"null"); 71. strcpy((*ptr).name,stdobj.name); 72. break; 73. } 74. 75. } 76. 77. //deattachingfrommemory 78. shmdt(ptr); 79. printf("deattachedsuccessfullyn"); 80. 81. } 82. else 83. perror("shmat"); 84. return 0; code: readFrom_sharedMemory.c 1. /* 2. Narayan Lal Menariya:August28,2018 3. 4. 5. * */ 6. 7. #include<stdio.h> 8. #include<sys/shm.h> 9. #include<sys/ipc.h> 10. #include "file.h" 11. int counter; 12. 13. struct student 14. { 15. intid; 16. char name[20]; 17. }stdobj; 18. 19. int main()
  • 7. 20. { 21. printf("counter:%dn",counter); 22. //creatingkeyforsharedmemory 23. key_tshmKey =100; 24. 25. struct student*ptr; 26. 27. //requestingkernel toreturnshemid 28. intshmid = shmget(shmKey,sizeof(stdobj),IPC_CREAT|0666);//key,size,flg|permission 29. 30. //attachingtosharedmemory 31. ptr = (struct student*)shmat(shmid,NULL,0);//id,address,flg,0: read-write operation 32. 33. 34. if(ptr>0) 35. { 36. printf("Attachedsuccessfullyn"); 37. // printf("counter:%dn",counter); 38. 39. while(1) 40. { 41. if(((*ptr).id==1) && (strcmp((*ptr).name,"null")==0)) 42. break; 43. while((*ptr).id==0) 44. { 45. sleep(1); 46. } 47. 48. while((*ptr).id!=0) 49. { 50. 51. //readingdatafromsharedmemoryat address= ptr 52. 53. if(((*ptr).id==1) && (strcmp((*ptr).name,"null")==0)) 54. break; 55. 56. printf("studentid:%dn",(*ptr).id); 57. printf("studentname :%sn",(*ptr).name); 58. 59. printf("Datareadsuccessfullyn"); 60. ptr++; 61. 62. //printf("counter:%dn",counter); 63. //counter--; 64. } 65. } 66. //deattachingfrommemory 67. shmdt(ptr); 68. printf("deattachedsuccessfullyn"); 69. 70. //removingsharedmemoryid
  • 8. 71. shmctl(shmid,IPC_RMID,0); 72. 73. } 74. else 75. perror("shmat"); 76. return 0; 77. } Happy to help. If you haveany doubt at anywherein codecan ask me. Thank you.