1 /* Test of flock() function.
2 Copyright (C) 2008 Free Software Foundation, Inc.
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 2 of the License, or
7 (at your option) any later version.
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.
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/>. */
24 #define ASSERT(expr) \
29 fprintf (stderr, "%s:%d: assertion failed, errno = %d\n", \
30 __FILE__, __LINE__, errno); \
38 test_shared (const char *file, int fd)
40 /* Should be able to acquire several shared locks on a file, through
41 * different file table entries.
45 ASSERT (flock (fd, LOCK_SH) == 0);
47 fd2 = open (file, O_RDWR, 0644);
50 r = flock (fd2, LOCK_SH | LOCK_NB);
51 ASSERT (r == 0); /* Was able to acquire a second shared lock. */
53 ASSERT (flock (fd, LOCK_UN) == 0);
54 ASSERT (close (fd2) == 0);
58 test_exclusive (const char *file, int fd)
60 /* Should not be able to acquire more than one exclusive lock on a file. */
63 ASSERT (flock (fd, LOCK_EX) == 0);
65 fd2 = open (file, O_RDWR, 0644);
68 r = flock (fd2, LOCK_SH | LOCK_NB);
69 ASSERT (r == -1); /* Was unable to acquire a second exclusive lock. */
71 ASSERT (flock (fd, LOCK_UN) == 0);
72 ASSERT (close (fd2) == 0);
76 main (int argc, char *argv[])
79 const char *file = "test-flock.txt";
81 /* Open a non-empty file for testing. */
82 fd = open (file, O_RDWR | O_CREAT | O_TRUNC, 0644);
84 ASSERT (write (fd, "hello", 5) == 5);
86 /* Some impossible operation codes which should never be accepted. */
87 ASSERT (flock (fd, LOCK_SH | LOCK_EX) == -1);
88 ASSERT (errno == EINVAL);
89 ASSERT (flock (fd, LOCK_SH | LOCK_UN) == -1);
90 ASSERT (errno == EINVAL);
91 ASSERT (flock (fd, LOCK_EX | LOCK_UN) == -1);
92 ASSERT (errno == EINVAL);
93 ASSERT (flock (fd, 0) == -1);
94 ASSERT (errno == EINVAL);
96 test_shared (file, fd);
97 test_exclusive (file, fd);
99 /* Close and remove the test file. */
100 ASSERT (close (fd) == 0);
101 ASSERT (unlink (file) == 0);