【问题标题】:File descriptor table - parent/child sharing it文件描述符表 - 父/子共享它
【发布时间】:2014-11-10 08:11:31
【问题描述】:

我正在尝试创建一个示例(以帮助我理解以下概念):

子进程继承其父进程的打开文件。 可以在这张图中看到http://www.cs.ucsb.edu/~rich/class/cs170/notes/FileSystem/filetable.rich.jpg

这是我的代码:

 FILE* f = fopen("test.txt", "r");

 if(fork()==0){

    printf("%c",  fgetc(f) ); //should print e
    printf("%c",  fgetc(f) ); //should print s
    printf("%c",  fgetc(f) ); //should print t
    printf("\n");
 } else {
    printf("%c",  fgetc(f) ); // print t

 }

test.txt 包含单词test

假设父母先运行,如果父母和孩子有相同的描述符表,系统不应该输出t(from parent)est(from children)。当前输出为t▒▒▒▒

谢谢 丹尼尔

【问题讨论】:

    标签: c unix posix


    【解决方案1】:

    C stdio 库使用缓冲来提高效率。即使您只读取一个字符,fgetc 函数也会从文件中读取整个缓冲区。对于这么小的文件,这意味着被调度的进程首先会完全读取它。

    您可以通过调用setvbuf 来禁用缓冲。或者,您可以使用直接对文件描述符进行操作的函数(openread)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2014-02-26
      • 2011-01-19
      • 1970-01-01
      • 2011-10-02
      • 2017-11-15
      相关资源
      最近更新 更多