You might open the file in the parent process before forking. Each child then can, according to this answer, just re-use the file descriptor and you should be fine.
Of course, you'd still need some means to synchronise your different processes such that writes to the file are interleaved properly (one process writing AB
and the other one C
resulting in ABC
or CAB
, but not ACB
...). Doing so is easier with threads, so if you can use them you might prefer them. Otherwise, this answer might be of interest to you.
Edit (according to new comments to question): If I understand correctly, you want to do the following:
- Parent process creates several child processes.
- Each child writes some information to a file.
- After each or all children having terminated, parent reads back the information from files.
You might do the following then:
- Parent process opens a new temporary file with with arbitrary name for each child - right before forking. This way, according to above, parent and child have the same file descriptors available.
- After forking, child process uses the file descriptor to write it's information to, parent process pushes the descriptor to e. g. a
std::vector
or, if more suitable, a std::map
mapping PID to FD.
- Parent process waits for children, on termination uses the file descriptors stored to read information back.
Have you considered using pipes instead? They might be the better alternative...