Clone(2) in Rust

I am trying to see if it's possible to use the clone system call in pure Rust (no ffi). I need to pass some extra flags while calling clone. I looked at std::process::Command but there does not seem to be a way to pass extra flags like CLONE_FS etc. Is there a way to do this in Rust?

How can arbitrary clone flags possibly be safe? Many of them create sharing, which can't safely be reasoned about across process boundaries.

FWIW, unix/process.rs doesn't directly use clone anyway, just libc::fork.

Perhaps this is an XY problem -- what specifically are you trying to accomplish?

1 Like

Thanks for the reply. However,

I never claimed they are. Not sure why you assumed I did. I am trying to see if I can re-write this piece of code in pure Rust https://gist.github.com/achanda/f623b172195d885e055afeff39f48dfe. Why? To learn Rust. Why? Free will, I guess?

You could have worded your reply better. The Rust community has always been very welcoming to experienced programmers and beginners (like me) alike. Let's keep it that way.

You can use the syscall crate (on crates.io) to call this syscall but I'm not sure why you don't want to just use the wrapper function in the libc crate (also on crates.io), unless its to learn how to call a syscall from Rust, I guess. Its not common to do a direct syscall from Rust.

I'm sorry if my tone sounded rude. I was merely trying be direct, to figure out what you really need. You're right that I made an assumption about wanting safety -- that's pretty much Rust's point. I guess if nothing else, the unsafety explains why general clone functionality wouldn't be present in libstd.

To present one alternative for your net namespace example, you could use the unstable before_exec to tweak a new process, perhaps calling libc::unshare with CLONE_NEWNS. (edit: or CLONE_NEWNET, of course.) That's still FFI, but at least in glibc it's a thin wrapper for the syscall. And this way you can keep some of Rust's safety around stack setup and such.

1 Like

Another option is nix::sched::clone, which is still FFI underneath, but you can use it with pure Rust.

1 Like