Skip to content

Commit

Permalink
close socket after releasing the socket
Browse files Browse the repository at this point in the history
  • Loading branch information
stlankes committed Aug 7, 2024
1 parent 0a5a68e commit 451c765
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions examples/vsock/src/vsock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};

#[cfg(target_os = "hermit")]
use hermit_abi::{
accept, bind, listen, read, sa_family_t, sockaddr, sockaddr_vm, socket, socklen_t, write,
AF_VSOCK, SOCK_STREAM, VMADDR_CID_ANY,
accept, bind, close, listen, read, sa_family_t, sockaddr, sockaddr_vm, socket, socklen_t,
write, AF_VSOCK, SOCK_STREAM, VMADDR_CID_ANY,
};
#[cfg(unix)]
use libc::{
accept, bind, c_void, listen, read, sa_family_t, sockaddr, sockaddr_vm, socket, socklen_t,
write, AF_VSOCK, SOCK_STREAM, VMADDR_CID_ANY,
accept, bind, c_void, close, listen, read, sa_family_t, sockaddr, sockaddr_vm, socket,
socklen_t, write, AF_VSOCK, SOCK_STREAM, VMADDR_CID_ANY,
};

pub type VsockAddr = sockaddr_vm;
Expand Down Expand Up @@ -99,7 +99,7 @@ fn check<T: std::ops::Neg<Output = T> + std::cmp::PartialOrd<T> + IsNegative>(
/// A virtio socket server, listening for connections.
#[derive(Debug)]
pub struct VsockListener {
socket: OwnedFd,
fd: OwnedFd,
}

impl VsockListener {
Expand Down Expand Up @@ -127,7 +127,7 @@ impl VsockListener {
check(listen(fd, 128))?;

Ok(VsockListener {
socket: OwnedFd::from_raw_fd(fd),
fd: OwnedFd::from_raw_fd(fd),
})
}
}
Expand All @@ -147,7 +147,7 @@ impl VsockListener {

let fd = unsafe {
check(accept(
self.socket.as_raw_fd(),
self.fd.as_raw_fd(),
&mut vsock_addr as *mut _ as *mut sockaddr,
&mut vsock_addr_len as *mut u32,
))?
Expand All @@ -157,6 +157,14 @@ impl VsockListener {
}
}

impl Drop for VsockListener {
fn drop(&mut self) {
unsafe {
let _ = close(self.fd.as_raw_fd());
}
}
}

pub struct VsockStream {
fd: OwnedFd,
}
Expand Down Expand Up @@ -212,3 +220,11 @@ impl Write for VsockStream {
Ok(())
}
}

impl Drop for VsockStream {
fn drop(&mut self) {
unsafe {
let _ = close(self.fd.as_raw_fd());
}
}
}

0 comments on commit 451c765

Please sign in to comment.