views:

83

answers:

2

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.

A: 

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.

Paul R
Ok, so can i do like this: dup2(filedescriptor2, filedescriptor1); and again dup2(filedescriptor3, filedescriptor1); dub2(filedescriptor4, filedescriptor1);
alaamh
No, dup2 just makes a new file descriptor refer to the same open file. You need to open the file 3 times and hand out those descriptors to the processes that need them.
nos
if you don't mind show me example.
alaamh
+1  A: 

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.

echo cat dog mouse fish bird | run_each prog1 prog2 prog3

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:

echo cat dog mouse fish bird > ./some-file.txt
run_each -stdin=./some-file.txt prog1 prog2 prog3

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.

nategoose