相当于 Unix 中的命名管道 LIFO/Stack 结构

Equivalent to named pipes in Unix for LIFO/Stack structure

我一直在查看所有不同类型的 Unix 文件:常规文件、目录、设备文件、符号文件 link、门、套接字、命名管道...

但我找不到 表现得像 stack/LIFO 结构的文件类型

众所周知,FIFO/named 管道相对于常规文件的优势如下:

来自 https://askubuntu.com/questions/449132/why-use-a-named-pipe-instead-of-a-file

几乎 Linux 中的所有内容都可以被视为文件,但是常规文件和命名管道之间的主要区别 是命名管道是文件的特殊实例,它具有文件系统上没有内容.

来自 man fifo

A FIFO special file (a named pipe) is similar to a pipe, except that it is accessed as part of the filesystem. It can be opened by multiple processes for reading or writing. When processes are exchanging data via the FIFO, the kernel passes all data internally without writing it to the filesystem. Thus, the FIFO special file has no contents on the filesystem; the filesystem entry merely serves as a reference point so that processes can access the pipe using a name in the filesystem.

The kernel maintains exactly one pipe object for each FIFO special file that is opened by at least one process. The FIFO must be opened on both ends (reading and writing) before data can be passed. Normally, opening the FIFO blocks until the other end is opened also.

所以我想知道这种类型的文件 (LIFO/Stack) 是否真的存在于 Unix 中?如果不是这样,有没有办法模拟一个?

我一直在考虑使用 tac <named_pipe> 但我不确定这是否是一个 good/viable 的想法?

有更好的解决方案吗?

感谢您的帮助。

Almost everything in Linux can be considered a file, but the main difference between a regular file and a named pipe is that a named pipe is a special instance of a file that has no contents on the filesystem.

更好的理解方式是命名管道是出现在文件系统中的管道。它没有存储在磁盘上的内容,但它也不仅仅是一个空 inode -- 它具有特定于管道的特定行为。

So I was wondering if this type of file (LIFO/Stack) does actually exist natively in Unix?

不,它不存在。与队列不同,堆栈不能被视为流;而且,无论如何,它在多进程环境中都不是特别有用的结构。并发处理多个进程没有意义 pushing/popping 来自堆栈的数据。

I have been thinking about using tac <named_pipe> but I am not sure if it is a good/viable idea?

那不行。 tac 将读取管道的全部内容,之后管道中将没有任何内容。

堆栈是一种非常有用且合理的结构。它非常适合 LIFO 任务处理程序,例如程序堆栈。 虽然通常不是多进程,但我只需要通过 pthreads 对此类使用进行多线程处理(线程之间的共享内存有助于减轻 IPC 的负担)并通过控制线程创建和终止来避免使用显式堆栈。如果您需要从共享堆栈中弹出线程,只要您正确地用互斥量阻塞了该线程和任何相关部分,就可以这样做。 (你需要决定是否同时发生推送和弹出,你的弹出是否应该等待推送完成以便你可以弹出刚刚推送的内容,或者等待弹出完成以便你的推送发生在下一层,或者先到先得。

如果您坚持使用多进程而不是单进程和多线程,您可以使用 IPC 管道和管理堆栈的附加进程来构建自己的实现。堆栈管理器将通过命名管道接受推送和弹出请求,并将弹出的数据推送到另一个命名管道。您必须构建您的数据,以便它可以与 push/pop 命令区分开来,或者将推送的数据放在第三个命名管道上。您必须了解管道缓冲区和使用情况,以免交叉或拆分流。