Rust 中的 Future 可以在不阻塞的情况下进行轮询,以检查 future 是否准备好(并在此过程中做一些工作)。考虑到这一点,是否可以在不消耗其输出的情况下“检查”未来是否已准备好?
stdin如果有任何数据,将会被轮询,并对输入(playground)采取行动:
async fn read_input_if_available() {
use tokio::io::AsyncReadExt;
let mut stdin = tokio::io::stdin();
// if !stdin.ready() {
// return;
// }
let mut input = String::new();
let mut buffer = [0_u8; 1024];
while let Ok(bytes) = stdin.read(&mut buffer).await {
if let Ok(string) = std::str::from_utf8(&buffer[..bytes]) {
input.push_str(string);
}
}
// Take action on `input` here
}
Run Code Online (Sandbox Code Playgroud)
当代码命中 时await,直到标准输入上有内容为止,即使只是等待EOF.
我使用tokio::io::Stdin它是因为它对于一个独立的示例来说更简单,但问题是关于 Rust 期货的。
背景:
我有一个进程,用于tokio::process在 tokio 运行时生成带有句柄的子进程。
它还负责在杀死子进程后释放资源,并且根据文档(std::process::Child、tokio::process::Child),这需要父进程wait()(或await在 tokio 中)进行该进程。
SIGINT并非所有进程对 a或 a 的行为都相同SIGTERM,因此我想在发送 a 之前给孩子一些时间来死掉SIGKILL。
所需的解决方案:
pub async fn kill(self) {
// Close input
std::mem::drop(self.stdin);
// Send gracefull signal
let pid = nix::unistd::Pid::from_raw(self.process.id() as nix::libc::pid_t);
nix::sys::signal::kill(pid, nix::sys::signal::SIGINT);
// Give the process time to die gracefully
if let Err(_) = tokio::time::timeout(std::time::Duration::from_secs(2), self.process).await
{
// Kill forcefully
nix::sys::signal::kill(pid, nix::sys::signal::SIGKILL);
self.process.await;
}
}
Run Code Online (Sandbox Code Playgroud)
但是给出了这个错误:
error[E0382]: use of moved value: `self.process` …Run Code Online (Sandbox Code Playgroud) 当调用一个不带 trait 的默认实现时self,为什么需要注释一个实现类型?
下面是一个最小的、可重复的示例(playground):
mod builder {
pub trait Builder: Sized {
fn new() -> Simple {
Simple
}
}
pub struct Simple;
impl Builder for Simple {}
}
pub fn main() {
let _ = builder::Builder::new();
/* Working version */
// use builder::Builder;
// let _ = builder::Simple::new();
}
Run Code Online (Sandbox Code Playgroud)
这使:
error[E0283]: type annotations needed
--> src/main.rs:14:13
|
3 | fn new() -> Simple {
| ------------------ required by `builder::Builder::new`
...
14 | let …Run Code Online (Sandbox Code Playgroud) 我正在测试一个java代码,我想打印1到10的数字
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;
public class test2
{
test2()
{
for (int i = 0; i<10; i++)
{
System.out.println(i);
if (i == 5)
break;
if (i == 6)
break;
System.out.println(i);
break;
}
}
public static void main(String[] args)
{
new test2();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我删除最后一个break,代码工作.但如果我不删除它,只会打印数字0.为什么?.
rust ×3
rust-tokio ×2
async-await ×1
asynchronous ×1
break ×1
for-loop ×1
java ×1
traits ×1
types ×1