fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <semaphore.h>
  5. #include <pthread.h>
  6.  
  7. static sem_t sem;
  8.  
  9. void *do_work(void *arg) {
  10. // if something fails
  11. printf("Something failed!\n");
  12. exit(1);
  13. }
  14.  
  15. void exit_handler() {
  16. sem_post(&sem); // wake up main thread
  17. sem_wait(&sem); // wait for cleanup in main
  18. sem_destroy(&sem);
  19. }
  20.  
  21. int main() {
  22. pthread_t worker_thread;
  23.  
  24. sem_init(&sem, 0, 0);
  25. atexit(exit_handler);
  26.  
  27. pthread_create(&worker_thread, NULL, do_work, NULL);
  28.  
  29. sem_wait(&sem); // block this thread until work is done
  30.  
  31. // simulate some cleanup
  32. usleep(1000000);
  33. printf("This never gets called!\n");
  34.  
  35. sem_post(&sem);
  36. }
  37.  
Runtime error #stdin #stdout 0s 10440KB
stdin
Standard input is empty
stdout
Something failed!