EOF在文件结束前到达

前端之家收集整理的这篇文章主要介绍了EOF在文件结束前到达前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在为学校制作一个程序,我有一个多进程程序,每个进程读取一个文件的一部分,它们一起工作来计算文件中的单词数.我有一个问题,如果有超过2个进程,那么所有进程在读取文件的部分之前从文件中读取EOF.这是相关的代码

#include dio.h>
#include 

使用3个进程运行文件时的输出

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)).

原文链接:https://www.f2er.com/linux/439813.html

猜你在找的Linux相关文章