update nearly all FSF copyright year lists to include 2010
[gnulib.git] / tests / nap.h
1 /* Assist in file system timestamp tests.
2    Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Eric Blake <ebb9@byu.net>, 2009.  */
18
19 #ifndef GLTEST_NAP_H
20 # define GLTEST_NAP_H
21
22 /* Sleep long enough to notice a timestamp difference on the file
23    system in the current directory.  Assumes that BASE is defined,
24    and requires that the test module depends on usleep.  */
25 static void
26 nap (void)
27 {
28   static long delay;
29   if (!delay)
30     {
31       /* Initialize only once, by sleeping for 20 milliseconds (needed
32          since xfs has a quantization of about 10 milliseconds, even
33          though it has a granularity of 1 nanosecond, and since NTFS
34          has a default quantization of 15.25 milliseconds, even though
35          it has a granularity of 100 nanoseconds).  If the seconds
36          differ, repeat the test one more time (in case we crossed a
37          quantization boundary on a file system with 1 second
38          resolution).  If we can't observe a difference in only the
39          nanoseconds, then fall back to 1 second if the time is odd,
40          and 2 seconds (needed for FAT) if time is even.  */
41       struct stat st1;
42       struct stat st2;
43       ASSERT (close (creat (BASE "tmp", 0600)) == 0);
44       ASSERT (stat (BASE "tmp", &st1) == 0);
45       ASSERT (unlink (BASE "tmp") == 0);
46       delay = 20000;
47       usleep (delay);
48       ASSERT (close (creat (BASE "tmp", 0600)) == 0);
49       ASSERT (stat (BASE "tmp", &st2) == 0);
50       ASSERT (unlink (BASE "tmp") == 0);
51       if (st1.st_mtime != st2.st_mtime)
52         {
53           /* Seconds differ, give it one more shot.  */
54           st1 = st2;
55           usleep (delay);
56           ASSERT (close (creat (BASE "tmp", 0600)) == 0);
57           ASSERT (stat (BASE "tmp", &st2) == 0);
58           ASSERT (unlink (BASE "tmp") == 0);
59         }
60       if (! (st1.st_mtime == st2.st_mtime
61              && get_stat_mtime_ns (&st1) < get_stat_mtime_ns (&st2)))
62         delay = (st1.st_mtime & 1) ? 1000000 : 2000000;
63     }
64   usleep (delay);
65 }
66
67 #endif /* GLTEST_NAP_H */