lockfd.c 799 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <pthread.h>
  2. #include <assert.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include "xalloc.h"
  7. static pthread_mutex_t **mutexes = NULL;
  8. static pthread_mutex_t *get_mutex(int fd)
  9. {
  10. assert(fd < 3 && "todo: implement generically");
  11. if (!mutexes) {
  12. mutexes = xmalloc(3*sizeof(char*));
  13. assert(mutexes);
  14. }
  15. if (!mutexes[fd]) {
  16. mutexes[fd] = xmalloc(sizeof(pthread_mutex_t));
  17. assert(mutexes[fd]);
  18. pthread_mutex_init(mutexes[fd], NULL);
  19. assert(mutexes[fd]);
  20. }
  21. return mutexes[fd];
  22. }
  23. int lock_fd(int fd)
  24. {
  25. return pthread_mutex_lock(get_mutex(fd));
  26. }
  27. int unlock_fd(int fd)
  28. {
  29. return pthread_mutex_unlock(get_mutex(fd));
  30. }
  31. int lock_file(FILE *f)
  32. {
  33. assert(f);
  34. return lock_fd(fileno(f));
  35. }
  36. int unlock_file(FILE *f)
  37. {
  38. assert(f);
  39. return unlock_fd(fileno(f));
  40. }