Adding support for in-place use of ProducerConsumerQueue.
[folly.git] / folly / test / EventFDTest.cpp
1 /*
2  * Copyright 2012 Facebook, Inc.
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 <gtest/gtest.h>
19 #include "folly/eventfd.h"
20 #include <glog/logging.h>
21
22 using namespace folly;
23
24 TEST(EventFD, Basic) {
25   int fd = eventfd(10, EFD_NONBLOCK);
26   CHECK_ERR(fd);
27   uint64_t val;
28   ssize_t r;
29   // Running this twice -- once with the initial value, and once
30   // after a write()
31   for (int attempt = 0; attempt < 2; attempt++) {
32     val = 0;
33     r = read(fd, &val, sizeof(val));
34     CHECK_ERR(r);
35     EXPECT_EQ(sizeof(val), r);
36     EXPECT_EQ(10, val);
37     r = read(fd, &val, sizeof(val));
38     EXPECT_EQ(-1, r);
39     EXPECT_EQ(EAGAIN, errno);
40     val = 10;
41     r = write(fd, &val, sizeof(val));
42     CHECK_ERR(r);
43     EXPECT_EQ(sizeof(val), r);
44   }
45   close(fd);
46 }
47
48 TEST(EventFD, Semaphore) {
49   int fd = eventfd(10, EFD_NONBLOCK | EFD_SEMAPHORE);
50   CHECK_ERR(fd);
51   uint64_t val;
52   ssize_t r;
53   // Running this twice -- once with the initial value, and once
54   // after a write()
55   for (int attempt = 0; attempt < 2; attempt++) {
56     val = 0;
57     for (int i = 0; i < 10; i++) {
58       r = read(fd, &val, sizeof(val));
59       CHECK_ERR(r);
60       EXPECT_EQ(sizeof(val), r);
61       EXPECT_EQ(1, val);
62     }
63     r = read(fd, &val, sizeof(val));
64     EXPECT_EQ(-1, r);
65     EXPECT_EQ(EAGAIN, errno);
66     val = 10;
67     r = write(fd, &val, sizeof(val));
68     CHECK_ERR(r);
69     EXPECT_EQ(sizeof(val), r);
70   }
71   close(fd);
72 }
73