Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
616041231bea6ca4a9bea7aa2f391580ffc895fb
[simgrid.git] / src / mc / remote / Channel.cpp
1 /* Copyright (c) 2015-2023. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "src/mc/remote/Channel.hpp"
8 #include <xbt/log.h>
9
10 #include <cerrno>
11 #include <cstring>
12 #include <sys/socket.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Channel, mc, "MC interprocess communication");
17
18 namespace simgrid::mc {
19
20 Channel::~Channel()
21 {
22   if (this->socket_ >= 0)
23     close(this->socket_);
24 }
25
26 /** @brief Send a message; returns 0 on success or errno on failure */
27 int Channel::send(const void* message, size_t size) const
28 {
29   if (size >= sizeof(int) && is_valid_MessageType(*static_cast<const int*>(message))) {
30     XBT_DEBUG("Sending %s (%zu bytes sent)", to_c_str(*static_cast<const MessageType*>(message)), size);
31   } else {
32     XBT_DEBUG("Sending bytes directly (from address %p) (%zu bytes sent)", message, size);
33     if (size == 0)
34       XBT_WARN("Request to send a 0-sized message! Proceeding anyway.");
35   }
36
37   while (::send(this->socket_, message, size, 0) == -1) {
38     if (errno != EINTR) {
39       XBT_ERROR("Channel::send failure: %s", strerror(errno));
40       return errno;
41     }
42   }
43   return 0;
44 }
45
46 ssize_t Channel::receive(void* message, size_t size) const
47 {
48   ssize_t res = recv(this->socket_, message, size, 0);
49   xbt_assert(res != -1, "Channel::receive failure: %s", strerror(errno));
50   if (static_cast<size_t>(res) >= sizeof(int) && is_valid_MessageType(*static_cast<const int*>(message))) {
51     XBT_DEBUG("Receive %s (requested %zu; received %zd at %p)", to_c_str(*static_cast<const MessageType*>(message)),
52               size, res, message);
53   } else {
54     XBT_DEBUG("Receive %zd bytes", res);
55   }
56   return res;
57 }
58 } // namespace simgrid::mc