简体   繁体   中英

Command `cargo run` leads to "No such file or directory"

I need to run tests that run separate processes with sudo privilege (as they need to run privileged instructions eg shmat ).

I use .cargo/config to run tests with sudo , this is what causes the error, removing it allows the test to work until it attempts shmat at which point it fails.

In a minimal reproducible example the error is:

thread 'tests::base' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/lib.rs:4:103
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

The layout of the project is:

.
├── .cargo/
│   └── config.toml
├── Cargo.lock
├── Cargo.toml
└── src/
    ├── lib.rs
    └── bin/
        └── new_process.rs

config.toml :

[target.x86_64-unknown-linux-gnu]
runner = 'sudo -E'

cargo.toml :

[package]
name = "mre"
version = "0.1.0"
[dependencies]
libc = "0.2.127"

lib.rs :

#[cfg(test)]
mod tests {
    #[test]
    fn base() {
        let output = std::process::Command::new("cargo").args(["run","--bin","new_process"]).output().unwrap();
        dbg!(output);
    }
}

new_process.rs :

fn main() {
    let shmid = libc::shmget(libc::IPC_PRIVATE, 1024*4, libc::IPC_CREAT);
    let shared_mem_ptr = libc::shmat(shmid, std::ptr::null(), 0);
    println!("hello world");
}

If you installed cargo via rustup , it will likely be installed in your home directory, and not globally like in /usr/bin/ .

On my machine:

$ which cargo
/home/linus/.cargo/bin/cargo

So under sudo, cargo is not found:

$ sudo cargo
sudo: cargo: command not found

This is the exact same error you got from unwrap ing the result of Command::new().output() . So it is not a rust problem; it's a linux problem.

  1. You could specify an absolute path to the cargo executable:
// in lib.rs base()

// Modify for the location of cargo on your machine
Command::new("/home/linus/.cargo/bin/cargo")
  1. Or you could create a symlink from /usr/bin/cargo/ to /home/linus/.cargo/bin/cargo :
sudo ln -s /home/linus/.cargo/bin/cargo /usr/bin/cargo

Then, cargo is also found using sudo.

  1. Or you could install cargo globally by using a standalone installer . See https://stackoverflow.com/a/65255288/14350146

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM