Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // prog1.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <sys/stat.h>
- int main() {
- int msqid;
- char pathname[] = "prog1.c";
- key_t key;
- int i, len, maxlen;
- struct mymsgbuf
- {
- long mtype;
- struct info {
- char mtext[81];
- int count;
- } a;
- } mybuf;
- /* Create or attach message queue */
- key = ftok(pathname, 0);
- (void) umask(0000);
- if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
- printf("Can\'t get msqid\n");
- exit(-1);
- }
- /* Send information */
- for (i = 1; i <= 5; i++) {
- mybuf.mtype = 1;
- strcpy(mybuf.a.mtext, "Hi, second. I'm first\n");
- len = sizeof(struct info);
- if (msgsnd(msqid, (struct msgbuf*) &mybuf, len, 0) < 0) {
- printf("Can\'t send message to queue\n");
- msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
- exit(-1);
- }
- maxlen = len;
- if ((len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, 2, 0)) < 0) {
- printf("Can\'t receive message from queue\n");
- exit(-1);
- }
- printf("I am first and I found string: %s", mybuf.a.mtext);
- }
- return 0;
- }
- // prog2.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <sys/stat.h>
- int main() {
- int msqid;
- char pathname[] = "prog1.c";
- key_t key;
- int i, len, maxlen;
- struct mymsgbuf
- {
- long mtype;
- struct info {
- char mtext[81];
- int count;
- } a;
- } mybuf;
- /* Create or attach message queue */
- key = ftok(pathname, 0);
- (void) umask(0000);
- if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){
- printf("Can\'t get msqid\n");
- exit(-1);
- }
- /* Send information */
- for (i = 1; i <= 5; i++) {
- mybuf.mtype = 2;
- strcpy(mybuf.a.mtext, "Hi, first. I'm second\n");
- len = sizeof(struct info);
- if (msgsnd(msqid, (struct msgbuf*) &mybuf, len, 0) < 0) {
- printf("Can\'t send message to queue\n");
- msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
- exit(-1);
- }
- maxlen = len;
- if ((len = msgrcv(msqid, (struct msgbuf *) &mybuf, maxlen, 1, 0)) < 0) {
- printf("Can\'t receive message from queue\n");
- exit(-1);
- }
- printf("I am second and I found string: %s", mybuf.a.mtext);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment