0

我试图让我的程序为每个孩子一次读取一行(每行包含一个 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;
    }
4

1 回答 1

1

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

子继承父的一组打开文件描述符的副本...

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

于 2013-12-09T04:23:12.237 回答