th0m45s5helby

user1.c

Dec 24th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/msg.h>
  7. #include <string.h>
  8. #define SERVER 1L
  9. typedef struct {
  10. long msg_to;
  11. long msg_fm;
  12. char buffer[BUFSIZ];
  13. } MESSAGE;
  14. int mid,n;
  15. key_t key;
  16. char buff[50];
  17. struct msqid_ds buf;
  18. MESSAGE msg;
  19. int main(int argc, char** argv) {
  20. key = ftok(".", 'z');
  21. mid = msgget(key, 0);
  22. //Aquiring Message Queue ID
  23. printf("Message Queue ID: %d\n", mid);
  24. printf("user1 ID: %ld\n", (long)getpid());
  25. printf("enter the msg u want to send\n");
  26. scanf("%s",buff);
  27. n=strlen(buff);
  28. int i = 0;
  29. for(i=0;i<=n;i++)
  30. {
  31. msg.buffer[i] = buff[i];
  32. }
  33. //Getting user1 PID and preparing message to message queue
  34. long iD = (long)getpid();
  35. msg.msg_to = SERVER;
  36. msg.msg_fm = (long)getpid();
  37. //Send message to Message Queue for user2, throws and error for invalid input
  38. if(msgsnd(mid, &msg, sizeof(msg.buffer), 0)==-1){
  39. perror("msgsnd");
  40. exit(-1);
  41. }
  42. //Client waits for response from Server, throws an error if invalid input
  43. if(msgrcv(mid, &msg, sizeof(msg), iD, 0)<0){
  44. perror("msgrcv");
  45. exit(-1); }
  46. //Displaying the message received .
  47. printf("Message recieved\n");
  48. printf("%s\n", msg.buffer);
  49. //Removing message queue
  50. msgctl(mid, IPC_RMID, (struct msqid_ds *) 0);
  51. //user1 exits
  52. return (EXIT_SUCCESS);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment