]>
git.proxmox.com Git - rustc.git/blob - vendor/rustix/tests/net/unix.rs
1 //! Test a simple Unix-domain socket server and client.
3 //! The client sends lists of integers and the server sends back sums.
5 // This test uses `AF_UNIX` with `SOCK_SEQPACKET` which is unsupported on macOS.
12 // This test uses `DecInt`.
13 #![cfg(feature = "itoa")]
14 #![cfg(feature = "fs")]
16 use rustix
::fs
::{cwd, unlinkat, AtFlags}
;
17 use rustix
::io
::{read, write}
;
19 accept
, bind_unix
, connect_unix
, listen
, socket
, AddressFamily
, Protocol
, SocketAddrUnix
,
22 use rustix
::path
::DecInt
;
24 use std
::str::FromStr
;
25 use std
::sync
::{Arc, Condvar, Mutex}
;
28 const BUFFER_SIZE
: usize = 20;
30 fn server(ready
: Arc
<(Mutex
<bool
>, Condvar
)>, path
: &Path
) {
31 let connection_socket
= socket(
33 SocketType
::SEQPACKET
,
38 let name
= SocketAddrUnix
::new(path
).unwrap();
39 bind_unix(&connection_socket
, &name
).unwrap();
40 listen(&connection_socket
, 1).unwrap();
43 let (lock
, cvar
) = &*ready
;
44 let mut started
= lock
.lock().unwrap();
49 let mut buffer
= vec
![0; BUFFER_SIZE
];
51 let data_socket
= accept(&connection_socket
).unwrap();
54 let nread
= read(&data_socket
, &mut buffer
).unwrap();
56 if &buffer
[..nread
] == b
"exit" {
59 if &buffer
[..nread
] == b
"sum" {
63 sum
+= i32::from_str(&String
::from_utf8_lossy(&buffer
[..nread
])).unwrap();
66 write(&data_socket
, DecInt
::new(sum
).as_bytes()).unwrap();
69 unlinkat(cwd(), path
, AtFlags
::empty()).unwrap();
72 fn client(ready
: Arc
<(Mutex
<bool
>, Condvar
)>, path
: &Path
, runs
: &[(&[&str], i32)]) {
74 let (lock
, cvar
) = &*ready
;
75 let mut started
= lock
.lock().unwrap();
77 started
= cvar
.wait(started
).unwrap();
81 let addr
= SocketAddrUnix
::new(path
).unwrap();
82 let mut buffer
= vec
![0; BUFFER_SIZE
];
84 for (args
, sum
) in runs
{
85 let data_socket
= socket(
87 SocketType
::SEQPACKET
,
91 connect_unix(&data_socket
, &addr
).unwrap();
94 write(&data_socket
, arg
.as_bytes()).unwrap();
96 write(&data_socket
, b
"sum").unwrap();
98 let nread
= read(&data_socket
, &mut buffer
).unwrap();
100 i32::from_str(&String
::from_utf8_lossy(&buffer
[..nread
])).unwrap(),
105 let data_socket
= socket(
107 SocketType
::SEQPACKET
,
111 connect_unix(&data_socket
, &addr
).unwrap();
112 write(&data_socket
, b
"exit").unwrap();
117 let ready
= Arc
::new((Mutex
::new(false), Condvar
::new()));
118 let ready_clone
= Arc
::clone(&ready
);
120 let tmp
= tempfile
::tempdir().unwrap();
121 let path
= tmp
.path().join("soccer");
122 let send_path
= path
.to_owned();
123 let server
= thread
::Builder
::new()
124 .name("server".to_string())
126 server(ready
, &send_path
);
129 let send_path
= path
.to_owned();
130 let client
= thread
::Builder
::new()
131 .name("client".to_string())
138 (&["4", "77", "103"], 184),
139 (&["5", "78", "104"], 187),
145 client
.join().unwrap();
146 server
.join().unwrap();