我正在为学校制作一个程序,我有一个多进程程序,每个进程读取一个文件的一部分,它们一起工作来计算文件中的单词数.我有一个问题,如果有超过2个进程,那么所有进程在读取文件的部分之前从文件中读取EOF.这是相关的代码:
#include dio.h>
#include
All files opened successfully
Process 2 found unexpected EOF at 1323008.
Process 1 found unexpected EOF at 823849.
Process 0 found unexpected EOF at 331776.
导致错误的测试文件:https://dl.dropboxusercontent.com/u/16835571/test34.txt
编译:
gcc main.c -o wordc-mp
并运行:
wordc-mp test34.txt 3
从“man fork”,你可以得到确认:
The child process is created with a single thread—the one
that
called fork(). The entire virtual address space of the parent is
replicated in the child,including the states of mutexes,condition
variables,and other pthreads objects; the use of pthread_atfork(3)
may be helpful for dealing with problems that this can cause.The child inherits copies of the parent’s set of open file descrip‐
tors. Each file descriptor in the child refers to the same open
file description (see open(2)) as the corresponding file descriptor
in the parent. This means that the two descriptors share open file
status flags,current file offset,and signal-driven I/O attributes
(see the description of F_SETOWN and F_SETSIG in fcntl(2)).