AmidamaruZXC

Untitled

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