• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <fcntl.h>
19 
20 #include <gtest/gtest.h>
21 
22 #include <sys/eventfd.h>
23 
24 #include "utils.h"
25 
TEST(eventfd,smoke)26 TEST(eventfd, smoke) {
27   constexpr unsigned int kInitialValue = 2;
28   int fd = eventfd(kInitialValue, EFD_NONBLOCK);
29   ASSERT_NE(-1, fd);
30 
31   eventfd_t value = 123;
32   ASSERT_EQ(0, eventfd_read(fd, &value));
33   ASSERT_EQ(kInitialValue, value);
34 
35   // Reading clears the counter.
36   ASSERT_EQ(-1, eventfd_read(fd, &value));
37   ASSERT_EQ(EAGAIN, errno);
38 
39   // Values written are added until the next read.
40   ASSERT_EQ(0, eventfd_write(fd, 1));
41   ASSERT_EQ(0, eventfd_write(fd, 1));
42   ASSERT_EQ(0, eventfd_write(fd, 1));
43 
44   ASSERT_EQ(0, eventfd_read(fd, &value));
45   ASSERT_EQ(3U, value);
46 
47   close(fd);
48 }
49 
TEST(eventfd,cloexec)50 TEST(eventfd, cloexec) {
51   constexpr unsigned int kInitialValue = 2;
52   int fd = eventfd(kInitialValue, EFD_CLOEXEC);
53   ASSERT_NE(-1, fd);
54   AssertCloseOnExec(fd, true);
55 
56   eventfd_t value = 123;
57   ASSERT_EQ(0, eventfd_read(fd, &value));
58   ASSERT_EQ(kInitialValue, value);
59 
60   close(fd);
61 
62   fd = eventfd(kInitialValue, EFD_NONBLOCK | EFD_CLOEXEC);
63   ASSERT_NE(-1, fd);
64   AssertCloseOnExec(fd, true);
65 
66   value = 123;
67   ASSERT_EQ(0, eventfd_read(fd, &value));
68   ASSERT_EQ(kInitialValue, value);
69 
70   close(fd);
71 }
72 
TEST(eventfd,semaphore)73 TEST(eventfd, semaphore) {
74   int fd = eventfd(3, EFD_NONBLOCK | EFD_SEMAPHORE);
75   ASSERT_NE(-1, fd);
76 
77   eventfd_t value = 123;
78   ASSERT_EQ(0, eventfd_read(fd, &value));
79   ASSERT_EQ(1U, value);
80 
81   value = 123;
82   ASSERT_EQ(0, eventfd_read(fd, &value));
83   ASSERT_EQ(1U, value);
84 
85   value = 123;
86   ASSERT_EQ(0, eventfd_read(fd, &value));
87   ASSERT_EQ(1U, value);
88 
89   // The counter is cleared after the initial value decrements to 0.
90   ASSERT_EQ(-1, eventfd_read(fd, &value));
91   ASSERT_EQ(EAGAIN, errno);
92 
93   close(fd);
94 }
95