使用 posix shell 将数据传递到子进程的单独输入文件描述符

使用 posix shell 将数据传递到子进程的单独输入文件描述符

在 posix shell 中,我想将数据传递到后台子进程文件描述符,并在父进程中处理子进程的输出。

请不要使用 mkfifo,只需标准 posix shell 文件描述符复制。没有非 posix 功能,如进程替换 ( <(cmd))。无中间文件。没有 /dev/fd 或 /dev/std{in,out,err} 或 /proc/pid。

像下面这样的东西(这是行不通的,所以我的概念,因此可能的一些评论注释,很混乱):

child()
{
  sed '1s|^|child: |;q'   # prepend 'child: ' to first input line and quit
}

exec 4>&1           # open file descriptor 4 duplicated as stdout

# give the shell some time to start the child, then send data to child via fd 4
{ sleep 2; echo foo >&4; } &

out=$(child 4<&0)   # connect fd 4 to stdin in child process

echo "out: $out"

我本来希望能'child: foo'看到out。但相反,我foo在标准输出上看到并且child()永远不会终止(很明显,数据不会进入子级的输入文件描述符)。

更新:根据请求添加用例。

在循环中,将数据发送到读取 stdin 的实用程序,而无需每次通过循环重新生成所述实用程序。每次通过循环都必须重新分叉/执行该实用程序,成本很高。所以...作为后台子进程运行实用程序(仅执行一次)并通过子进程可用的输入文件描述符从父进程发送数据。

更新2

我想我真的在尝试做 mkfifo 所做的事情(创建一对输入/输出 fd,其中父级中的输出 fd 连接到子级的输入 fd,并将子级的 out fd 连接到 in fd父级),但没有 mkfifo 可用(如果可能的话,没有临时管道文件 - 即,仅使用匿名文件描述符)。

答案1

相关内容