EternalHaru

Untitled

May 28th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 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 <termios.h>
  11. #include <sys/select.h>
  12. #include <sys/ioctl.h>
  13. #include <cstring>
  14.  
  15. using namespace std;
  16.  
  17. typedef struct Arguments {
  18.     bool* flag;
  19.     int* fd;
  20. } arguments;
  21.  
  22.  
  23. int _kbhit() {
  24. static const int STDIN = 0;
  25. static bool initialized = false;
  26. if (! initialized) {
  27.     termios term;
  28.     tcgetattr(STDIN, &term);
  29.     term.c_lflag &= ~ICANON;
  30.     tcsetattr(STDIN, TCSANOW, &term);
  31.     setbuf(stdin, NULL);
  32.     initialized = true;
  33. }
  34. int bytesWaiting;
  35. ioctl(STDIN, FIONREAD, &bytesWaiting);
  36. return bytesWaiting;
  37. }
  38.  
  39.  
  40. void *tread(void *args) {
  41.     puts("write thread started");
  42.     arguments *argument = (arguments*)args;
  43.     char msg[] = "LETI 2018 OS";
  44.     while (*(argument->flag)) {
  45.         write(*(argument->fd), msg, strlen(msg));
  46.         printf("Writed: %s\n", msg);
  47.         fflush(stdout);
  48.         sleep(1);
  49.     }
  50.     printf("write thread finished\n");
  51.     fflush(stdout);
  52.     pthread_exit(NULL);
  53. }
  54.        
  55.        
  56. int main() {
  57.     char fifo_name[] = "current_fifo_name";
  58.     pthread_t threadInit;
  59.     bool flag = true;
  60.     arguments args;
  61.     int fd;
  62.    
  63.     unlink(fifo_name);
  64.    
  65.     if(mkfifo(fifo_name, 0777) == -1)
  66.         perror("mkfifo");
  67.    
  68.     fd = open(fifo_name, O_WRONLY | O_NONBLOCK);
  69.    
  70.     while((fd==-1)&&(!_kbhit())){
  71.         fd = open(fifo_name, O_WRONLY | O_NONBLOCK);
  72.         perror("open:");
  73.         sleep(1);
  74.     }
  75.    
  76.     args.fd = &fd;
  77.     args.flag = &flag;
  78.    
  79.     if(pthread_create(&threadInit, NULL, &tread, (void*)&args))
  80.         EXIT_FAILURE;
  81.    
  82.     getchar();
  83.    
  84.     flag = false;
  85.    
  86.     pthread_join(threadInit, NULL);
  87.    
  88.     close(fd);
  89.     unlink(fifo_name);
  90.     return EXIT_SUCCESS;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment