tst-flock1.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Copyright (C) 2002 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <pthread.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. #include <sys/file.h>
  20. static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  21. static int fd;
  22. static void *
  23. tf (void *arg)
  24. {
  25. if (flock (fd, LOCK_SH | LOCK_NB) != 0)
  26. {
  27. puts ("second flock failed");
  28. exit (1);
  29. }
  30. pthread_mutex_unlock (&lock);
  31. return NULL;
  32. }
  33. static int
  34. do_test (void)
  35. {
  36. char tmp[] = "/tmp/tst-flock1-XXXXXX";
  37. fd = mkstemp (tmp);
  38. if (fd == -1)
  39. {
  40. puts ("mkstemp failed");
  41. exit (1);
  42. }
  43. unlink (tmp);
  44. write (fd, "foobar xyzzy", 12);
  45. if (flock (fd, LOCK_EX | LOCK_NB) != 0)
  46. {
  47. puts ("first flock failed");
  48. exit (1);
  49. }
  50. pthread_mutex_lock (&lock);
  51. pthread_t th;
  52. if (pthread_create (&th, NULL, tf, NULL) != 0)
  53. {
  54. puts ("pthread_create failed");
  55. exit (1);
  56. }
  57. pthread_mutex_lock (&lock);
  58. void *result;
  59. if (pthread_join (th, &result) != 0)
  60. {
  61. puts ("pthread_join failed");
  62. exit (1);
  63. }
  64. close (fd);
  65. return result != NULL;
  66. }
  67. #define TEST_FUNCTION do_test ()
  68. #include "../test-skeleton.c"