如何在linux中创建一个文件描述符,可以从多个进程中读取而不消耗数据?

时间:2022-11-27 02:49:53

I'd like to create a file descriptor that when written to can be read from multiple processes without consuming the data. I'm aware of named pipes, but since it's a fifo, only one processes can ever get the data.

我想创建一个文件描述符,当写入时可以从多个进程中读取而不消耗数据。我知道命名管道,但由于它是一个fifo,只有一个进程可以获取数据。

My use case is the following. With git, hooks use stdin to pass data to be processed into the hook. I want to be able to call multiple sub-hooks from a parent hook. Each sub-hook should get the same stdin data as the parent receives. If I'm not mistaken when I use a pipe, then each subprocess will not get the same stdin. Instead, the first hook to read stdin would consume the data. Is this correct?

我的用例如下。使用git,钩子使用stdin将要处理的数据传递到钩子中。我希望能够从父钩子调用多个子钩子。每个子钩子应该获得与父接收的相同的stdin数据。如果我在使用管道时没有弄错,那么每个子进程都不会获得相同的stdin。相反,读取stdin的第一个钩子会消耗数据。它是否正确?

The only option I really see being viable at this point is writing stdin to a file then reading that file from each subprocess. Is there another way?

我真正看到的唯一选择是将stdin写入文件,然后从每个子进程读取该文件。还有另一种方式吗?

1 个解决方案

#1


1  

Perhaps you could try to use tee.

也许你可以尝试使用T恤。

From man tee:

从男士T恤:

tee - read from standard input and write to standard output and files

In your case with processes in this way: tee >(parent) >(hook1) >(hook2) >(hookn)

在你的情况下以这种方式处理:tee>(parent)>(hook1)>(hook2)>(hookn)

(where each hook is a different process, command, shell whatever you want)

(每个钩子都是不同的进程,命令,shell,无论你想要什么)

Here an example:

这是一个例子:

#!/bin/bash

while read stdinstream
do
    echo -n ${stdinstream} | tee >(parent) >(hook2) >(hook1)
done

EDIT:

编辑:

In your case I do not think you are going to need the while loop, with this could be enough:

在你的情况下,我不认为你将需要while循环,这可能就足够了:

read stdinstream
echo -n ${stdinstream} | tee >(parent) >(hook2) >(hook1)

Hopefully this will help you.

希望这会对你有所帮助。

#1


1  

Perhaps you could try to use tee.

也许你可以尝试使用T恤。

From man tee:

从男士T恤:

tee - read from standard input and write to standard output and files

In your case with processes in this way: tee >(parent) >(hook1) >(hook2) >(hookn)

在你的情况下以这种方式处理:tee>(parent)>(hook1)>(hook2)>(hookn)

(where each hook is a different process, command, shell whatever you want)

(每个钩子都是不同的进程,命令,shell,无论你想要什么)

Here an example:

这是一个例子:

#!/bin/bash

while read stdinstream
do
    echo -n ${stdinstream} | tee >(parent) >(hook2) >(hook1)
done

EDIT:

编辑:

In your case I do not think you are going to need the while loop, with this could be enough:

在你的情况下,我不认为你将需要while循环,这可能就足够了:

read stdinstream
echo -n ${stdinstream} | tee >(parent) >(hook2) >(hook1)

Hopefully this will help you.

希望这会对你有所帮助。