code_junkie

How to join a thread that is hanging on blocking IO?

Nov 11th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <signal.h>
  5.  
  6. int global_gotsig = 0;
  7.  
  8. void *gotsig(int sig, siginfo_t *info, void *ucontext)
  9. {
  10. global_gotsig++;
  11. return NULL;
  12. }
  13.  
  14. void *reader(void *arg)
  15. {
  16. char buf[32];
  17. int i;
  18. int hdlsig = (int)arg;
  19.  
  20. struct sigaction sa;
  21. sa.sa_handler = NULL;
  22. sa.sa_sigaction = gotsig;
  23. sa.sa_flags = SA_SIGINFO;
  24. sigemptyset(&sa.sa_mask);
  25.  
  26. if (sigaction(hdlsig, &sa, NULL) < 0) {
  27. perror("sigaction");
  28. return (void *)-1;
  29. }
  30. i = read(fileno(stdin), buf, 32);
  31. if (i < 0) {
  32. perror("read");
  33. } else {
  34. printf("Read %d bytesn", i);
  35. }
  36. return (void *)i;
  37. }
  38.  
  39. main(int argc, char **argv)
  40. {
  41. pthread_t tid1;
  42. void *ret;
  43. int i;
  44. int sig = SIGUSR1;
  45.  
  46. if (argc == 2) sig = atoi(argv[1]);
  47. printf("Using sig %dn", sig);
  48.  
  49. if (pthread_create(&tid1, NULL, reader, (void *)sig)) {
  50. perror("pthread_create");
  51. exit(1);
  52. }
  53. sleep(5);
  54. printf("killing threadn");
  55. pthread_kill(tid1, sig);
  56. i = pthread_join(tid1, &ret);
  57. if (i < 0)
  58. perror("pthread_join");
  59. else
  60. printf("thread returned %ldn", (long)ret);
  61. printf("Got sig? %dn", global_gotsig);
  62.  
  63. }
  64.  
  65. while (!_finished)
  66. {
  67. pthread_cond_wait(&cond);
  68. handleio();
  69. }
  70. cleanup();
  71.  
  72. struct pollfd pfd;
  73. pfd.fd = socket;
  74. pfd.events = POLLIN | POLLHUP | POLLERR;
  75. pthread_lock(&lock);
  76. while(thread_alive)
  77. {
  78. int ret = poll(&pfd, 1, 100);
  79. if(ret == 1)
  80. {
  81. //handle IO
  82. }
  83. else
  84. {
  85. pthread_cond_timedwait(&lock, &cond, 100);
  86. }
  87. }
  88. pthread_unlock(&lock);
Add Comment
Please, Sign In to add comment