Home > Software engineering >  Different Seek Pointer for read\write
Different Seek Pointer for read\write

Time:10-09

I am trying to understand how the seek pointer mechanism works when a parent process opens a new file and then creating a new child process using fork().

Assume I have the following code :

int main(){
int fd = open("myFile.txt", O_RDWR | O_CREAT)
if(fork() == 0){
 write(fd,"stack overflow", 16);
 close(fd);
}
else{
 wait(NULL);
 char buff[17];
 read(fd, &buff, 16);
 printf("%s", buff);
}

}

I get nothing printing to stdout, but I don't really understand why would it behave that way. Wouldn't it be smarter if there were a different seek pointer for read and write so running this code will result in printing "stack overflow" to stdout?

Apparently not, Would like to get an explanation

CodePudding user response:

Both processes are using the same file description (i.e. the same open file).

They are accessing the same file pointer because it's part of the same file description. When one of them writes some characters, the file pointer advances for all of them, because it's the same file pointer.

You can get the file pointer by calling lseek(fd, 0, SEEK_CUR). If you print the file pointer before starting the child program, and after waiting for it, you should see that it has changed.

  • Related