Back to index

glibc  2.9
tst-flock1.c
Go to the documentation of this file.
00001 /* Copyright (C) 2002 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003    Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #include <pthread.h>
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <unistd.h>
00024 #include <sys/file.h>
00025 
00026 
00027 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
00028 
00029 static int fd;
00030 
00031 
00032 static void *
00033 tf (void *arg)
00034 {
00035   if (flock (fd, LOCK_SH | LOCK_NB) != 0)
00036     {
00037       puts ("second flock failed");
00038       exit (1);
00039     }
00040 
00041   pthread_mutex_unlock (&lock);
00042 
00043   return NULL;
00044 }
00045 
00046 
00047 static int
00048 do_test (void)
00049 {
00050   char tmp[] = "/tmp/tst-flock1-XXXXXX";
00051 
00052   fd = mkstemp (tmp);
00053   if (fd == -1)
00054     {
00055       puts ("mkstemp failed");
00056       exit (1);
00057     }
00058 
00059   unlink (tmp);
00060 
00061   write (fd, "foobar xyzzy", 12);
00062 
00063   if (flock (fd, LOCK_EX | LOCK_NB) != 0)
00064     {
00065       puts ("first flock failed");
00066       exit (1);
00067     }
00068 
00069   pthread_mutex_lock (&lock);
00070 
00071   pthread_t th;
00072   if (pthread_create (&th, NULL, tf, NULL) != 0)
00073     {
00074       puts ("pthread_create failed");
00075       exit (1);
00076     }
00077 
00078   pthread_mutex_lock (&lock);
00079 
00080   void *result;
00081   if (pthread_join (th, &result) != 0)
00082     {
00083       puts ("pthread_join failed");
00084       exit (1);
00085     }
00086 
00087   close (fd);
00088 
00089   return result != NULL;
00090 }
00091 
00092 #define TEST_FUNCTION do_test ()
00093 #include "../test-skeleton.c"