fseek ftell reading same input

361 views Asked by At

I am trying to get my program to read one line at a time for each child (each line contains one int). Every time I perform this read, it keeps reading the first line.

Here is the basis of my code.

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;
    }
1

There are 1 answers

2
EyalAr On

Once you fork, each child has its own PCB. Since you open the file after the fork, then each child has it's own separate file descriptor, offset, etc.
If you want child processes to share the same file descriptor and offset, they have to point to the same file descriptor the kernel creates. For this, you have to open the file before the fork.
Read here for more information.

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

In your code, you try to keep track of the position in the file by using int tell, but this variable is not shared between the child processes. Instead, use a shared file descriptor and the kernel will keep track of the offset for you.