Advertisement
AmidamaruZXC

Untitled

May 8th, 2020
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include <time.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/ipc.h>
  5. #include <sys/msg.h>
  6. #include <string.h>
  7. #include <stdio.h>
  8. #include <stdbool.h>
  9.  
  10. #define MSG_LEN 100
  11.  
  12. int main() {
  13.  
  14.     srand(time(NULL));
  15.  
  16.     int msqid;
  17.  
  18.     char pathname[] = "09-4server.c";
  19.  
  20.     key_t key;
  21.  
  22.     int len, maxlen;
  23.  
  24.     struct clientmsgbuf {
  25.         long mtype;
  26.         struct {
  27.             pid_t pid;
  28.             char message[MSG_LEN];
  29.         } info;
  30.     } clientbuf;
  31.  
  32.     struct servermsgbuf {
  33.         long mtype;
  34.         struct {
  35.             char message[MSG_LEN];
  36.         } info;
  37.     } serverbuf;
  38.  
  39.     if ((key = ftok(pathname, 0)) < 0) {
  40.         printf("Can't generate key\n");
  41.         exit(-1);
  42.     }
  43.  
  44.     if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) {
  45.         printf("Can't get msqid\n");
  46.         exit(-1);
  47.     }
  48.  
  49.     clientbuf.mtype = 1;
  50.     clientbuf.info.pid = getpid();
  51.  
  52.     len = sizeof(clientbuf.info);
  53.     sprintf(clientbuf.info.message, "%d", rand());
  54.  
  55.     printf("Client #%d sends message %s\n", clientbuf.info.pid, clientbuf.info.message);
  56.     if (msgsnd(msqid, (struct clientmsgbuf *) &clientbuf, len, 0) < 0) {
  57.         printf("Can't send message to queue\n");
  58.         msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL);
  59.         exit(-1);
  60.     }
  61.  
  62.     printf("Waiting for response\n");
  63.  
  64.     maxlen = sizeof(serverbuf.info);
  65.     if (len = msgrcv(msqid, &serverbuf, maxlen, getpid(), 0) < 0) {
  66.         printf("Can't receive message from queue\n");
  67.         exit(-1);
  68.     }
  69.     printf("Server: %s\n", serverbuf.info.message);
  70.  
  71.     return 0;
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement