1//===-- Interactive unittests for select ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/errno/libc_errno.h"
10#include "src/sys/select/select.h"
11#include "src/unistd/read.h"
12#include "test/UnitTest/Test.h"
13
14#include <sys/select.h>
15#include <unistd.h>
16
17// This test is not be run automatically as part of the libc testsuite.
18// Instead, one has to run it manually and press a key on the keyboard
19// to make the test succeed.
20TEST(LlvmLibcSelectTest, ReadStdinAfterSelect) {
21 LIBC_NAMESPACE::libc_errno = 0;
22 constexpr int STDIN_FD = 0;
23 fd_set set;
24 FD_ZERO(&set);
25 FD_SET(STDIN_FD, &set);
26 struct timeval zero {
27 .tv_sec: 0, .tv_usec: 0
28 }; // No wait
29 struct timeval hr {
30 .tv_sec: 3600, .tv_usec: 0
31 }; // Wait for an hour.
32
33 // Zero timeout means we don't wait for input. So, select should return
34 // immediately.
35 int count =
36 LIBC_NAMESPACE::select(nfds: STDIN_FD + 1, read_set: &set, write_set: nullptr, error_set: nullptr, timeout: &zero);
37 // The set should indicate that stdin is NOT ready for reading.
38 ASSERT_EQ(0, FD_ISSET(STDIN_FD, &set));
39
40 FD_SET(STDIN_FD, &set);
41 // Wait for an hour and give the user a chance to hit a key.
42 count = LIBC_NAMESPACE::select(nfds: STDIN_FD + 1, read_set: &set, write_set: nullptr, error_set: nullptr, timeout: &hr);
43 ASSERT_EQ(count, 1);
44 // The set should indicate that stdin is ready for reading.
45 ASSERT_EQ(1, FD_ISSET(STDIN_FD, &set));
46
47 // Verify that atleast one character can be read.
48 char c;
49 ASSERT_EQ(LIBC_NAMESPACE::read(STDIN_FD, &c, 1), ssize_t(1));
50}
51

source code of libc/test/src/sys/select/select_ui_test.cpp