gpt4 book ai didi

c - fseek ftell 读取相同的输入

转载 作者:行者123 更新时间:2023-11-30 15:41:36 25 4
gpt4 key购买 nike

我试图让我的程序为每个 child 一次读取一行(每行包含一个 int)。每次我执行此读取时,它都会继续读取第一行。

这是我的代码的基础。

void forkChildren (int nChildren) {
int i;
int size;
int sum = 0;
int tell = 0;
pid_t pid;
for (i = 0; i < nChildren; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
return;
}
if (pid == 0) {
char data[10];
FILE * file1;
file1 = fopen("numbers.dat", "r");
fseek(file1, tell, SEEK_SET);
fgets(data, 10, file1);
//fseek(file1, tell, SEEK_SET);
tell += strlen(data);
printf("%d ", tell);
sum = atoi(data);
printf("Sum is: %d \n", sum);
sleep (5);
return;
}

最佳答案

一旦你 fork ,每个 child 都有自己的PCB 。由于您在 fork 之后打开文件,因此每个子文件都有自己单独的文件描述符、偏移量等。
如果您希望子进程共享相同的文件描述符和偏移量,它们必须指向内核创建的相同文件描述符。为此,您必须 fork 之前打开文件。
Read here了解更多信息。

The child inherits copies of the parent's set of open file descriptors...

在您的代码中,您尝试使用 inttell 来跟踪文件中的位置,但该变量在子进程之间共享。相反,使用共享文件描述符,内核将为您跟踪偏移量。

关于c - fseek ftell 读取相同的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com