tst-flock1.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #include <pthread.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <unistd.h>
  20. #include <sys/file.h>
  21. static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  22. static int fd;
  23. static void *
  24. tf (void *arg)
  25. {
  26. if (flock (fd, LOCK_SH | LOCK_NB) != 0)
  27. {
  28. puts ("second flock failed");
  29. exit (1);
  30. }
  31. pthread_mutex_unlock (&lock);
  32. return NULL;
  33. }
  34. static int
  35. do_test (void)
  36. {
  37. char tmp[] = "/tmp/tst-flock1-XXXXXX";
  38. fd = mkstemp (tmp);
  39. if (fd == -1)
  40. {
  41. puts ("mkstemp failed");
  42. exit (1);
  43. }
  44. unlink (tmp);
  45. write (fd, "foobar xyzzy", 12);
  46. if (flock (fd, LOCK_EX | LOCK_NB) != 0)
  47. {
  48. puts ("first flock failed");
  49. exit (1);
  50. }
  51. pthread_mutex_lock (&lock);
  52. pthread_t th;
  53. if (pthread_create (&th, NULL, tf, NULL) != 0)
  54. {
  55. puts ("pthread_create failed");
  56. exit (1);
  57. }
  58. pthread_mutex_lock (&lock);
  59. void *result;
  60. if (pthread_join (th, &result) != 0)
  61. {
  62. puts ("pthread_join failed");
  63. exit (1);
  64. }
  65. close (fd);
  66. return result != NULL;
  67. }
  68. #define TEST_FUNCTION do_test ()
  69. #include "../test-skeleton.c"