fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <pthread.h>
  6. #include <sys/select.h>
  7.  
  8. typedef struct _pipe_backed_thing_t {
  9. int pipes[2];
  10. char data[8192];
  11. } pipe_backed_thing_t;
  12.  
  13. void *routine(void *arg) {
  14. pipe_backed_thing_t *borrowed =
  15. (pipe_backed_thing_t *) arg;
  16.  
  17. /* link does thing */
  18. memcpy(borrowed->data, "hello world", sizeof("hello world") - 1);
  19.  
  20. /* if channel_is_observed_for_example() */
  21. write(borrowed->pipes[1],
  22. "\0", /* dummy packet null char */
  23. sizeof(char));
  24.  
  25. return NULL;
  26. }
  27.  
  28. int main(int argc, char** argv) {
  29. pipe_backed_thing_t thing;
  30.  
  31. if (0 != pipe(thing.pipes)) {
  32. exit(1);
  33. }
  34. /* 0 = read end, 1 = write end */
  35.  
  36. pthread_t thread;
  37.  
  38. if (0 != pthread_create(&thread, NULL, routine, (void*)&thing)) {
  39. exit(1);
  40. }
  41.  
  42. fd_set readfds;
  43. int rfd = thing.pipes[0];
  44.  
  45. FD_ZERO(&readfds);
  46. FD_SET(rfd, &readfds);
  47.  
  48. int ready = select(rfd + 1, &readfds, NULL, NULL, NULL);
  49.  
  50. if (ready == -1) {
  51. perror("select");
  52. exit(1);
  53. }
  54.  
  55. if (FD_ISSET(rfd, &readfds)) {
  56. char dummy;
  57. read(rfd, &dummy, sizeof(dummy));
  58. printf("got signal, data = %s\n", thing.data);
  59. }
  60.  
  61. pthread_join(thread, NULL);
  62.  
  63. close(thing.pipes[0]);
  64. close(thing.pipes[1]);
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
got signal, data = hello world