@@ -4,6 +4,7 @@ use i3stat::error::Result;
44use i3stat:: util:: route:: InterfaceUpdate ;
55use i3stat:: util:: { local_block_on, netlink_ipaddr_listen} ;
66use serde_json:: json;
7+ use tokio:: io:: { stdout, AsyncWriteExt } ;
78use tokio:: sync:: mpsc;
89
910#[ derive( Debug , Parser ) ]
@@ -30,21 +31,20 @@ fn main() -> Result<()> {
3031
3132 let ( output, _) = local_block_on ( async {
3233 let ( manual_tx, manual_rx) = mpsc:: channel ( 1 ) ;
33- manual_tx. send ( ( ) ) . await ?;
34-
3534 let mut rx = netlink_ipaddr_listen ( manual_rx) . await ?;
35+ manual_tx. send ( ( ) ) . await ?;
3636
3737 if let Command :: Info = args. command {
3838 match rx. recv ( ) . await {
39- Some ( interfaces) => print_interfaces ( & interfaces) . await ,
39+ Some ( interfaces) => print_interfaces ( & interfaces) . await ? ,
4040 None => println ! ( "null" ) ,
4141 }
4242
4343 return Ok ( ( ) ) ;
4444 }
4545
4646 while let Some ( interfaces) = rx. recv ( ) . await {
47- print_interfaces ( & interfaces) . await ;
47+ print_interfaces ( & interfaces) . await ? ;
4848 }
4949
5050 Err ( "Unexpected end of netlink subscription" . into ( ) )
@@ -53,9 +53,9 @@ fn main() -> Result<()> {
5353 output
5454}
5555
56- async fn print_interfaces ( interfaces : & InterfaceUpdate ) {
57- println ! (
58- "{}" ,
56+ async fn print_interfaces ( interfaces : & InterfaceUpdate ) -> Result < ( ) > {
57+ let s = format ! (
58+ "{}\n " ,
5959 json!(
6060 join_all( interfaces. values( ) . map( |interface| async {
6161 json!( {
@@ -80,6 +80,14 @@ async fn print_interfaces(interfaces: &InterfaceUpdate) {
8080 . await
8181 )
8282 ) ;
83+
84+ // flush output each time to facilitate common usage patterns like
85+ // `i3stat-net watch | while read x; do ... done`, etc.
86+ let mut stdout = stdout ( ) ;
87+ stdout. write_all ( s. as_bytes ( ) ) . await ?;
88+ stdout. flush ( ) . await ?;
89+
90+ Ok ( ( ) )
8391}
8492
8593#[ cfg( test) ]
0 commit comments