多个打开文件同时读取
我想使用 dup2 从输入文件中读取并将其重定向到 exec 函数的输入。但我的问题是我有三个正在运行的进程,它们都必须打开相同的输入文件,但它们执行不同的工作。在这种情况下你的建议是什么?我不知道是否可以使用“cat data.txt”为其他三个进程提供输入,但我不知道如何做到这一点。
I want to use dup2 to read from input file and redirect it to the input of exec function. but my problem is i have three running process all of them have to open same input file but they do different jobs. what your suggest in such case? i don't know if it is possible to use "cat data.txt" to feed the input for the three other process but i don't know the way to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果每个读者通过重复的文件描述符访问该文件,那么他们将共享文件偏移量,这可能会导致问题。
如果在上面的示例中,程序 run_each 要打开以命令行参数给出的运行程序,并为每个程序提供标准输入的重复版本,则 prog1 可能会读取“cat”,prog2 可能会读取“dog mouse”,而 prog3 可能会读取“ 鸟”。在这种情况下,从长远来看,调用 dup2 实际上不会执行任何操作。
如果我们更改 run_each 程序以采用参数 -stdin= ,使其打开并 dup2 该文件作为每个子程序的标准输入,则:
在这个示例中,这可能更接近您正在处理的内容,因为它使用如果是可查找的普通文件,您将遇到与第一个示例相同的问题,因为每个 prog# 的所有标准输入文件共享偏移/查找位置。
如果每个程序都调用 pread 来进行所有读取(假设读取已完成,但还有一个 pwrite),那么它在此示例中将起作用(但第一个不起作用),但您确实应该打开文件多次,这样每个子程序就不必知道其标准输入可能发生什么情况。
If each reader gets access to the file through dup-ed file discriptors then they will all share the file offset which could cause problems.
If in the above example the program run_each were to open run programs given as command line arguments giving them each a dup-ed version of it's standard input then prog1 might read "cat", prog2 might read " dog mouse", and prog3 might read " bird". In this case calling dup2 would not actually have done anything in the long run.
If we change our run_each program to take a parameter -stdin= which makes it open and dup2 that file as standard input for each child program then:
In this example, which is probably a little closer to what you are dealing with since it uses a normal file which is seekable you would have the same problems as in the first example because all of the standard input files of each prog# share the offset/seek position.
If each of the programs called pread for all of their reading (assuming reading was all that was done, but there is also a pwrite) then it would work in this example (but the first wouldn't work), but you really should open the file several times so that each of the child programs doesn't have to have any idea of what else might be going on with it's standard input.
只要您不写入该文件,而仅读取该文件,那么有多少进程正在读取该文件就无关紧要。
So long as you are not writing to this file, only reading from it, then it shouldn't matter how many processes are reading it.