Search code examples
rustipcmmap

Process A creates a file through mmap and returns fd. How does process B read the mmap created by process A?


Passing large objects between processes is what I want. There are two process, process A create mmap file, and process B read the mmap.

Process A: Create an object with mmap

#[cfg(test)]
mod tests {

use std::fs::File;
use std::os::unix::io::AsRawFd;
use bytes::Bytes;
use memmap::Mmap;
use tempfile::tempfile;

#[test]
fn test_tmp_file_mmap() {
    let file = tempfile().unwrap();
    file.set_len(100).unwrap();
    println!("fd = {}", file.as_raw_fd());
    let mmap = unsafe {
        Mmap::map(&file).unwrap()
    };
    let mut_mmap = mmap.make_mut().unwrap();
    // write something into mut_mmap

}

}

Cargo.toml

memmap = "0.7.0"
tempfile = "3.3.0"

I know that the fd of the same file may be different in different processes. But the different fd in multi-process point to the same file in Open File Table of kernel.

Process B:How to get the same mmap in process B using fd of process A (I do not know the file name as I am using tempfile)? Or is there any other way to get the mmap of process A without using the filename in rust?

I have seen the code for the c related implementation, but it seems that process B gets mmap directly through process A's fd using sendmsg. (I suspect there is some conversion inside)


Solution

  • The Rust equivalent of using C to transmit an fd via sendmsg already exists in the passfd crate. Once the file descriptor is passed, you can make a memory map from it in the normal way.