使用文件作为两个程序的生产者消费者系统的缓冲区

发布于 2024-12-05 22:06:19 字数 255 浏览 2 评论 0原文

我有两个程序,其中一个将一些条目写入文件,另一个程序从文件中读取所有条目并处理它们。

目前,文件是按顺序执行的。这意味着,第一个程序完全生成文件并在第二个程序运行之前退出。现在我希望,无需太多修改,第二个程序就可以以生产者-消费者的方式同时运行。我知道我应该使用进程间通信,但此时我想对程序进行最小的更改才能运行。

具体来说,我希望第二个程序实时处理第二个文件中的条目,因为它们是由第一个文件生成的。

我在 ubuntu 11.04 上使用 gcc

I have two programs one of which writes some entries into a file and the other one reads all the entries from the file an processes them.

Currently, the files are executed sequentially. That means, the first programs produces the file completely and exits before the second program is run. Now I want, without much modifications that the second program can be run simultaneously in a producer-consumer fashion. I know I should use interprocess communication, but at this point I want to make minimal changes the programs to get the running.

Specifically, I want that the second program processes the entries from the second file in real time as they are generated by the first file.

I am using gcc on ubuntu 11.04

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

信仰 2024-12-12 22:06:19

如果您使用的是类 Unix 操作系统,我可以建议使用管道吗?修改您的第一个程序以写入标准输出(而不是打开文件并传递 ofstream 的引用,而是传递 std::cout)。修改您的第二个程序以从标准输入读取(同上,但将您的 ifstream 引用替换为 std::cin)。

然后,不要这样做

prog1 -o some-tmp-file.txt
prog2 -i some-tmp-file.txt

prog1 | prog2


EDIT: If your existing programs are based on <cstdio> instead of <iostream>, the same principle applies. Use stdout instead of your existing FILE* in the first program. Uses stdin instead of your FILE* in the second program.


EDIT #2: If you want to make absolutely no change to the second program, and perhaps only minimal changes to the first program, try using named pipes.

mkfifo /tmp/some-tmp-file.txt
prog2 -i /tmp/some-temp-file.txt &
prog1 -o /tmp/some-temp-file.txt

If you are using a Unix-like operating system, may I suggest pipes? Modify your first program to write to standard output (instead of opening a file and passing references that ofstream around, pass std::cout). Modify your 2nd program to read from standard input (ditto, but replace your ifstream references with std::cin).

Then, instead of

prog1 -o some-tmp-file.txt
prog2 -i some-tmp-file.txt

do this:

prog1 | prog2


EDIT: If your existing programs are based on <cstdio> instead of <iostream>, the same principle applies. Use stdout instead of your existing FILE* in the first program. Uses stdin instead of your FILE* in the second program.


EDIT #2: If you want to make absolutely no change to the second program, and perhaps only minimal changes to the first program, try using named pipes.

mkfifo /tmp/some-tmp-file.txt
prog2 -i /tmp/some-temp-file.txt &
prog1 -o /tmp/some-temp-file.txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文