瀏覽代碼

Unix and net sockets started

devel
Ludovic 'Archivist' Lagouardette 5 年之前
父節點
當前提交
f0103d8284
共有 1 個檔案被更改,包括 52 行新增2 行删除
  1. +52
    -2
      include/shared_fd.hpp

+ 52
- 2
include/shared_fd.hpp 查看文件

@ -3,6 +3,8 @@
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <atomic>
#include <cassert>
@ -47,6 +49,31 @@ namespace gp{
sticky_bit = S_ISVTX,
};
enum class net_socket_domain : int {
ip4 = AF_INET,
ip6 = AF_INET6
};
enum class net_socket_protocol : int {
tcp = SOCK_STREAM,
udp = SOCK_DGRAM
};
using socket_opt_flags = int;
enum class net_socket_opt_flags : socket_opt_flags {
non_blocking = SOCK_NONBLOCK,
close_on_exec = SOCK_CLOEXEC,
};
using socket_opt_flags = int;
enum class unix_socket_opt_flags : socket_opt_flags {
non_blocking = SOCK_NONBLOCK,
close_on_exec = SOCK_CLOEXEC,
};
class shared_fd {
int fd;
std::atomic_int* guard;
@ -64,7 +91,7 @@ namespace gp{
, last_error(0)
{}
shared_fd(shared_fd& oth)
shared_fd(k">const shared_fd& oth)
: fd(oth.fd)
, guard(oth.guard)
, last_error(0)
@ -82,7 +109,7 @@ namespace gp{
oth.guard=nullptr;
}
void operator=(shared_fd& oth)
void operator=(k">const shared_fd& oth)
{
this->~shared_fd();
fd = oth.fd;
@ -109,6 +136,29 @@ namespace gp{
return ret;
}
static shared_fd net_socket(const net_socket_domain& dom, const net_socket_protocol& proto, net_socket_opt_flags& flags)
{
shared_fd ret{::socket((int)dom, (int)proto, (int)flags)};
return ret;
}
static shared_fd unix_socket(const net_socket_protocol& proto, const socket_opt_flags flags) {
shared_fd ret{::socket((int)AF_UNIX, (int)proto, (int)flags)};
return ret;
}
static std::pair<shared_fd,shared_fd> unix_socketpair(const net_socket_protocol& proto, const socket_opt_flags flags) {
std::pair<gp::shared_fd, gp::shared_fd> ret;
int fds[2];
auto result = ::socketpair((int)AF_UNIX, (int)proto, (int)flags, fds);
if(result != 0)
return ret;
ret.first = shared_fd(fds[0]);
ret.second = shared_fd(fds[1]);
return ret;
}
bool is_valid() const {
return guard && (fd>=0);
}

Loading…
取消
儲存