Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <string.h>
- #define SERVER 1L
- typedef struct {
- long msg_to;
- long msg_fm;
- char buffer[BUFSIZ];
- } MESSAGE;
- int mid,n;
- key_t key;
- char buff[50];
- struct msqid_ds buf;
- MESSAGE msg;
- int main(int argc, char** argv) {
- //Creating a message queue
- key = ftok(".", 'z');
- if((mid = msgget(key, IPC_CREAT | 0660))<0){
- printf("Error Creating Message Queue\n");
- exit(-1);
- }
- //Display Message Queue and Server ID
- printf("Message Queue ID: %d\n", mid);
- printf("user2 ID: %ld\n", (long)getpid());
- //Receiving message from user1, throws and error if input is invalid
- if(msgrcv(mid, &msg, sizeof(msg.buffer), SERVER, 0)<0){
- perror("msgrcv");
- exit(-1);
- }
- //user2 displays received message
- printf("user2 receives:\n");
- printf("%s\n", msg.buffer);
- //Aquiring user1 PID to message return
- long client = msg.msg_fm;
- printf("enter the message to send \n");
- scanf("%s",buff);
- n=strlen(buff);
- for(int i=0;i<=n;i++)
- {
- msg.buffer[i]=buff[i];
- }
- //prep return message
- msg.msg_fm = SERVER;
- msg.msg_to = client;
- //send converting message back to client, throws and error if input is invalid
- if(msgsnd(mid, (struct MESSAGE*)&msg, sizeof(msg.buffer), 0)==-1){
- perror("msgsnd");
- exit(-1);
- }
- //server exits
- return (EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment