AmidamaruZXC

Untitled

May 8th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/ipc.h>
  3. #include <sys/msg.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <time.h>
  9.  
  10. struct request_msg_buf {
  11.     long mtype;
  12.     struct {
  13.         pid_t client_pid;
  14.         long n;
  15.     } info;
  16. };
  17.  
  18. struct response_msg_buf {
  19.     long mtype;
  20. };
  21.  
  22. int main() {
  23.  
  24.     srand(time(NULL));
  25.  
  26.     int msqid; // IPC-дескриптор очереди сообщений
  27.  
  28.     char pathname[] = "server.c";
  29.  
  30.     key_t key; // IPC-ключ
  31.  
  32.     struct request_msg_buf request;
  33.     struct response_msg_buf response;
  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.     request.mtype = 1;
  46.  
  47.     request.info.client_pid = getpid();
  48.  
  49.     request.info.n = (rand() % 11) - 5;
  50.  
  51.     if (msgsnd(msqid, (struct msgbuf*) &request, sizeof(request.info), 0) < 0) {
  52.         printf("Can't send message to queue\n");
  53.         msgctl(msqid, IPC_RMID, (struct msqid_ds*) NULL);
  54.         exit(-1);
  55.     }
  56.  
  57.     if (request.info.n >= 0)
  58.         printf("Freeing up %ld resources\n", request.info.n);
  59.     else
  60.         printf("Waiting for %ld resources\n", -request.info.n);
  61.     msgrcv(msqid, (struct msgbuf*) &response, 0, request.info.client_pid, 0);
  62.  
  63.     printf("All right, process is terminated.\n");
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment