Advertisement
_takumi

server.c

Mar 4th, 2023
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <sys/mman.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8.  
  9. #include "message.h"
  10.  
  11. const char* shar_object = "posix-shar-object";
  12.  
  13. void sys_err (char *msg) {
  14.   puts (msg);
  15.   exit (1);
  16. }
  17.  
  18. int keepRunning = 1;
  19. void intHandler(int dummy) {
  20.     keepRunning = 0;
  21. }
  22.  
  23. int main () {
  24.   int shmid;
  25.   message_t *msg_p;      
  26.  
  27.   if ( (shmid = shm_open(shar_object, O_CREAT|O_RDWR, 0666)) == -1 ) {
  28.     perror("shm_open");
  29.     sys_err ("server: object is already open");
  30.   } else {
  31.     printf("Object is open: name = %s, id = 0x%x\n", shar_object, shmid);
  32.   }
  33.   if (ftruncate(shmid, sizeof (message_t)) == -1) {
  34.     perror("ftruncate");
  35.     sys_err ("server: memory sizing error");
  36.     return 1;
  37.   } else {
  38.     printf("Memory size set and = %lu\n", sizeof (message_t));
  39.   }
  40.  
  41.   msg_p = mmap(0, sizeof (message_t), PROT_WRITE|PROT_READ, MAP_SHARED, shmid, 0);
  42.   if (msg_p == (message_t*)-1 ) {
  43.   }
  44.  
  45.   signal(SIGINT, intHandler);
  46.   msg_p->type = MSG_TYPE_EMPTY;
  47.   while (1) {
  48.     if (keepRunning) {
  49.       if (msg_p->type != MSG_TYPE_EMPTY) {
  50.         if (msg_p->type == MSG_TYPE_STRING) {
  51.           printf ("%d\n", msg_p->n);
  52.         } else if (msg_p->type == MSG_TYPE_FINISH) {
  53.           break;
  54.         }
  55.         msg_p->type = MSG_TYPE_EMPTY;
  56.       }
  57.     } else {
  58.       msg_p->type = MSG_TYPE_FINISH;
  59.     }
  60.   }
  61.  
  62.   if(shm_unlink(shar_object) == -1) {
  63.     perror("shm_unlink");
  64.     sys_err ("server: error getting pointer to shared memory");
  65.   }
  66.   return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement