EternalHaru

Untitled

May 28th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 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 <errno.h>
  10. #include <time.h>
  11.  
  12. using namespace std;
  13.  
  14. typedef struct Arguments {
  15.     bool* flag;
  16.     timespec* tm;
  17.     int* fd;
  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 (read(*(argument->fd), buf, 100) <= 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("write thread finished\n");
  38.     fflush(stdout);
  39.     pthread_exit(NULL);
  40. }
  41.        
  42.  
  43. int main() {
  44.     char fifo_name[] = "current_fifo_name";
  45.     pthread_t threadInit;
  46.     bool flag = true;
  47.     arguments args;
  48.     timespec tm;
  49.     int fd;
  50.  
  51.     unlink(fifo_name);
  52.    
  53.     mkfifo(fifo_name, 0777);
  54.    
  55.     fd = open(fifo_name, O_RDONLY | O_NONBLOCK);
  56.    
  57.     args.flag = &flag;
  58.     args.fd = &fd;
  59.     args.tm = &tm;
  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.     close(fd);
  71.     unlink(fifo_name);
  72.     return EXIT_SUCCESS;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment