fork() 中文件描述符的行为

发布于 2024-12-09 10:27:14 字数 749 浏览 0 评论 0原文

当子进程从父进程中派生时,父进程中的所有变量都会复制到新的子进程中。因此,当我们在分叉发生之前打开一个公共文件,并尝试从父级和子级读取同一文件时,两者都应该独立打印结果。但是当我尝试实现这一点时,从文件中读取的父级和子级似乎是交错的。需要知道为什么会发生这种情况。当从父进程派生新进程时,甚至文件描述符也应该被复制。那么出了什么问题呢?

#include<stdio.h>
#include<fcntl.h>

main()
{
int fp;
char buff[11];
int pid;
fp = open("file1.txt", O_RDONLY);
pid = fork();
if(pid==0)
{
    printf("Child begins %d\n", getpid());
    read(fp, buff, 5);
    buff[10] = '\0';
    printf("Child read:");
    puts(buff);
    printf("Child exiting\n");
}
else
{
    read(fp, buff, 5);
    buff[10] = '\0';
    printf("Parent read:");
    puts(buff);
    printf("Parent exiting\n");
}
 }

现在假设 file1.txt 的内容为“Hello world”,那么父进程和子进程都应该打印“Hello”。但我看到的是儿童/家长打印“Hello”中的一个,另一个打印“world”。

When a child is forked from a parent process, all the variables from the parent are copied to the new child process. Hence when we open a common file before the fork happens, and try to read the same file both from parent and child, both should print results independently. But when i try to implement this, the reading from file for parent and child seems to be interleaved. Need to know as to why is this happening. Even the file descriptor should be duplicated when a new process is forked from the parent. So whats going wrong ?

#include<stdio.h>
#include<fcntl.h>

main()
{
int fp;
char buff[11];
int pid;
fp = open("file1.txt", O_RDONLY);
pid = fork();
if(pid==0)
{
    printf("Child begins %d\n", getpid());
    read(fp, buff, 5);
    buff[10] = '\0';
    printf("Child read:");
    puts(buff);
    printf("Child exiting\n");
}
else
{
    read(fp, buff, 5);
    buff[10] = '\0';
    printf("Parent read:");
    puts(buff);
    printf("Parent exiting\n");
}
 }

Now suppose the file1.txt has the content "Hello world", then both the parent and child processes should have printed "Hello". But what i see is one among child/parent prints "Hello" and the other prints " world".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒路情人 2024-12-16 10:27:14

文件描述符是重复的,但重复项指向系统文件表中的相同条目,因此两个进程共享相同的文件指针。内核 read() 和 writes() 是原子的,因此每个进程在文件指针被另一个进程移动后都会看到该指针。

The file descriptors are duplicated, but the duplicates point to the SAME entry in the system file table, so the two processes share the same file pointer. Kernel read()'s and writes()'s are atomic, so each process will see the file pointer after it has been moved by the other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文