EternalHaru

Untitled

May 28th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <sys/stat.h>
  2. #include <sys/types.h>
  3. #include <fcntl.h>
  4. #include <pthread.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <mqueue.h>
  10.  
  11. using namespace std;
  12.  
  13.  
  14. typedef struct Arguments {
  15.     bool* flag;
  16.     timespec* tm;
  17.     mqd_t* mqid;
  18. } arguments;
  19.  
  20.  
  21. void *thread(void *args) {
  22.     puts("read thread started");
  23.     arguments *argument = (arguments*) args;
  24.     (*(argument->tm)).tv_sec = 0;
  25.     (*(argument->tm)).tv_nsec = 100000000;
  26.     char buf[100];
  27.     while (*(argument->flag)) {
  28.         while ((mq_receive(*(argument->mqid), buf, 100, 0)) <= 0) {
  29.             if (!*(argument->flag))
  30.                 return 0;
  31.             nanosleep(argument->tm, NULL);
  32.         }      
  33.         printf("Readed: %s\n", buf);
  34.         fflush(stdout);
  35.         sleep(1);
  36.     }
  37.     printf("read thread finished");
  38.     fflush(stdout);
  39.     pthread_exit(NULL);
  40. }
  41.  
  42. int main() {
  43.     char mq_name[] = "/message_queue";
  44.     bool flag = true;
  45.     pthread_t threadInit;
  46.     arguments args;
  47.     mq_attr attr;
  48.     timespec tm;
  49.     mqd_t mqid;
  50.    
  51.    
  52.     tm.tv_sec = 0;
  53.     tm.tv_nsec = 100000000;
  54.     attr = {O_NONBLOCK, 10, 64, 0};
  55.     mqid = mq_open(mq_name, O_CREAT | O_RDONLY | O_NONBLOCK, 0777, &attr);  
  56.    
  57.     args.flag = &flag;
  58.     args.tm = &tm;
  59.     args.mqid = &mqid;
  60.    
  61.     if(pthread_create(&threadInit, NULL, &thread,(void*) &args))
  62.         return EXIT_FAILURE;
  63.    
  64.     getchar();
  65.    
  66.     flag = false;
  67.    
  68.     pthread_join(threadInit, NULL);  
  69.    
  70.     mq_close(mqid);
  71.     mq_unlink(mq_name);
  72.     return EXIT_SUCCESS;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment