Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 11th, 2012  |  syntax: None  |  size: 1.26 KB  |  hits: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Cancelling getchar()
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <sys/select.h>
  6.  
  7. void * entry_point(void * p) {
  8.     int readpipe = *(int *)p;
  9.     fd_set rfds;
  10.  
  11.     char c;
  12.  
  13.     for (;;) {
  14.         FD_ZERO(&rfds);
  15.         FD_SET(STDIN_FILENO, &rfds);
  16.         FD_SET(readpipe, &rfds);
  17.  
  18.         while (select(readpipe + 1, &rfds, NULL, NULL, NULL) == 0);
  19.  
  20.         if (FD_ISSET(readpipe, &rfds)) {
  21.             close(readpipe);
  22.             break;
  23.         }
  24.  
  25.         if (FD_ISSET(STDIN_FILENO, &rfds)) {
  26.             if (read(STDIN_FILENO, &c, sizeof(c)) > 0) {
  27.                 printf("Read: %dn", c);
  28.             }
  29.         }
  30.     }
  31.  
  32.     printf("Thread terminatingn");
  33.  
  34.     pthread_exit(NULL);
  35. }
  36.  
  37. int main() {
  38.     pthread_t thread;
  39.     int r;
  40.     int pipes[2];
  41.  
  42.     pipe(pipes);
  43.  
  44.     if (r = pthread_create(&thread, NULL, entry_point, &pipes[0])) {
  45.         printf("Error: %dn", r);
  46.         return 1;
  47.     }
  48.  
  49.     sleep(5);
  50.  
  51.     printf("Closing pipe and joining thread.n");
  52.  
  53.     close(pipes[1]);
  54.     pthread_join(thread, NULL);
  55.  
  56.     pthread_exit(NULL);
  57. }
  58.        
  59. $ time ./test
  60. 1
  61. Read: 49
  62. Read: 10
  63. 2
  64. Read: 50
  65. Read: 10
  66. 3
  67. Read: 51
  68. Read: 10
  69. 4
  70. Read: 52
  71. Read: 10
  72. 5
  73. Read: 53
  74. Read: 10
  75. Closing pipe and joining thread.
  76. Thread terminating
  77.  
  78. real    0m5.004s
  79. user    0m0.004s
  80. sys     0m0.000s