如何使用Unix套接字对传递Rust和Ruby进程

问题描述 投票:1回答:1

我试图使用Unix套接字对使用子Ruby进程传递Rust进程。我只使用Ruby尝试过相同的功能,但它似乎无法使用Rust。

我已经尝试将“rust_socket”文件描述符传递给Ruby脚本,将“ruby_socket”文件描述符传递给Ruby以及读取/写入套接字的不同组合。我觉得我应该传递“ruby_socket”文件描述符,但是当我这样做时,我得到一个错误的文件描述符错误。

// The rust side of things
use std::process::Command;
use std::os::unix::net::UnixStream;
use std::os::unix::io::IntoRawFd;
use std::io::{Read, Write};

fn main() {
    let (rust_socket, mut ruby_socket) = match UnixStream::pair() {
        Ok((rust_socket, ruby_socket)) => (rust_socket, ruby_socket),
        Err(e) => {
            println!("Failed to open socket pair: {:?}", e);
            return;
        }
    };

    let _output = Command::new("ruby")
        .args(&["/home/station/workspace/rust_server/src/client.rb", &rust_socket.into_raw_fd().to_string()])
        .spawn()
        .expect("Failed to start ruby process");

    let mut response = String::new();
    ruby_socket.read_to_string(&mut response).unwrap();
}
# The ruby side of things
require "socket"

begin
  socket = UNIXSocket.for_fd(ARGV.shift.to_i)
  socket.send("Hello world!\n", 0)
ensure
  socket&.close
end

我希望能够读到“Hello world!”来自Rust的字符串,但它不起作用。

ruby sockets rust unix-socket
1个回答
0
投票

问题似乎是Rust sets all file descriptors to be closed when a child is created by setting the FD_CLOEXEC flag。解决这个问题的唯一方法似乎是使用libc来调用fcntl

这里有一些似乎有效的代码,但我不知道Rust,所以使用风险自负。你将遇到的另一个问题是你需要在产生孩子后关闭rust_socket的父方面,否则read_to_string将永远阻止等待关闭流。您可以使用drop执行此操作,但您还需要使用AsRawFd而不是IntoRawFd

use std::process::Command;
use std::os::unix::net::UnixStream;
use std::os::unix::io::AsRawFd;
use std::io::Read;

extern crate libc;

fn main() {
    // Create the socket pair.
    let (rust_socket, mut ruby_socket) = UnixStream::pair().unwrap();

    // Unset FD_CLOEXEC on the socket to be passed to the child.
    let fd = rust_socket.as_raw_fd();
    unsafe {
        let flags = libc::fcntl(fd, libc::F_GETFD);
        libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
    }

    // Spawn the child
    let _output = Command::new("ruby")
        .args(&["client.rb", &fd.to_string()])
        .spawn();

    // After spawning, close the parents side of rust_socket.
    // If we use IntoRawFd, rust_socket would have been moved by this point
    // so we need AsRawFD instead.
    drop(rust_socket);

    let mut response = String::new();
    ruby_socket.read_to_string(&mut response).unwrap();

    println!("Ruby said '{}'", response);
}
© www.soinside.com 2019 - 2024. All rights reserved.