我正在try 使用fork()创建子进程并通过管道进行通信.我使用的是nix库和os_pive.当我try 执行该程序时,它正在等待,并且我看不到我在子进程中向父进程发送的消息.我试着用Drop功能来关闭管道,但没有起作用.这是我的代码:

use nix::sys::wait::wait;
use nix::unistd::ForkResult::{Child, Parent};
use nix::unistd::{fork, getpid, getppid, pipe};
use std::io::prelude::*;

fn main() {
    let pid = fork();
    let (mut reader, mut writer) = os_pipe::pipe().unwrap();

    match pid.expect("Error during creating child") {
        Parent { child } => {
            println!("From parent, {}", getpid());
            wait().unwrap();
            let mut data = String::new();
            reader.read_to_string(&mut data).unwrap();
            println!("data: {}", data);
        }

        Child => {
            println!("from child, {}", getpid());
            writer.write_all("hello".as_bytes()).unwrap();
        }
    }
}

谢谢!

推荐答案

首先,您呼叫fork(),然后创建管道.一旦fork()返回,就有两个过程(假设fork()返回两次).这意味着每个进程创建一个彼此无关的单独管道对.只需交换这两行,这样就只有一个共享管道(您还忘记了unsafe):

    let (mut reader, mut writer) = os_pipe::pipe().unwrap();
    let pid = unsafe { fork() };

然后,在Forking 之后,管道的每一端都有两个副本,但由于父管道仅执行读操作,而子管道仅执行写入操作,因此您应该关闭(drop)未使用的端:

    match pid.expect("Error during creating child") {
        Parent { child } => {
            drop(writer);
            //...
        }
        Child => {
            drop(reader);
            //...
        }

如果没有关闭父级中的编写器,即使子级结束,管道仍将是opened for writing,而父级永远不会到达管道的末端,read_to_string()永远不会结束.drop(reader)在这里实际上并不需要,但不管怎样,它都是一个很好的实践:子元素可以利用未能写入管道来检测父母已经死亡.

Linux相关问答推荐

如何在Linux上获取clang中的模板实例化统计?

从一个文件中读取文件名并将文件名和内容存储到另一个带有|的文件中作为分隔符

为什么waitpid(2)可以指定非子进程?

使用awk命令将以:分隔的两个文件合并的方法

如何让xargs对 bash 脚本中find命令找到的所有文件执行?

Google Cloud Ops Agent Mongo 集成错误 - AuthenticationFailed:SCRAM 身份验证失败,storedKey 不匹配

如何使用 Bash 将随机数据块写入文件

使用具有特定值的字段对文件进行排序

进程Forking 后 pthread_key_create() 生成的密钥会发生什么?

我可以阅读 Linux 内核的哪些部分以获得乐趣?

XML 编辑/查看软件

如何克隆 OpenLDAP 数据库

如果关键字触发然后执行命令,Shell 脚本来监视日志(log)文件?

如何在 Linux 上传递带感叹号的参数?

从 FTP 服务器下载所有文件

在 bash 中将输出作为 cp 的参数传递

svn over HTTP 代理

Linux(Ubuntu)终端-如何查看以前的页面不再可见

当我已经 ssh 进入远程机器时,如何 scp 回到本地?

Ionic android 构建错误 - 找不到ANDROID_HOME环境变量