github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/socket_blocking.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include "test/syscalls/linux/socket_blocking.h"
    16  
    17  #include <sys/socket.h>
    18  #include <sys/types.h>
    19  #include <sys/un.h>
    20  
    21  #include <cstdio>
    22  
    23  #include "gtest/gtest.h"
    24  #include "absl/time/clock.h"
    25  #include "absl/time/time.h"
    26  #include "test/syscalls/linux/socket_test_util.h"
    27  #include "test/syscalls/linux/unix_domain_socket_test_util.h"
    28  #include "test/util/test_util.h"
    29  #include "test/util/thread_util.h"
    30  #include "test/util/timer_util.h"
    31  
    32  namespace gvisor {
    33  namespace testing {
    34  
    35  TEST_P(BlockingSocketPairTest, RecvBlocks) {
    36    auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
    37  
    38    char sent_data[100];
    39    RandomizeBuffer(sent_data, sizeof(sent_data));
    40  
    41    constexpr auto kDuration = absl::Milliseconds(200);
    42    auto before = Now(CLOCK_MONOTONIC);
    43  
    44    const ScopedThread t([&]() {
    45      absl::SleepFor(kDuration);
    46      ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),
    47                  SyscallSucceedsWithValue(sizeof(sent_data)));
    48    });
    49  
    50    char received_data[sizeof(sent_data)] = {};
    51    ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
    52                                 sizeof(received_data), 0),
    53                SyscallSucceedsWithValue(sizeof(received_data)));
    54  
    55    auto after = Now(CLOCK_MONOTONIC);
    56    EXPECT_GE(after - before, kDuration);
    57  }
    58  
    59  }  // namespace testing
    60  }  // namespace gvisor