fork() fd

I run this code, actually I want to both processes print the message from "data". But only one does. What happens? Anyone can help?

#include <stdio.h>
main(){

int fd, pid;
char x;

fd = open("data",0); /* open file "data" */
pid = fork();

if(pid != 0){
wait(0);
printf("PID = %d.\n", getpid());
printf("FD = %d.\n",fd);
while (read(fd, &x, 1)){
write(1, &x, 1);
}
}
else{
printf("PID = %d.\n", getpid());
printf("PD= %d.\n",fd);
while (read(fd, &x, 1))
write(1, &x, 1);
}
}

The out put from the code:

This is a test.
PID = 4985.
PD= 3.
PID = 4984.
FD = 3.

When you open() a file you create an entry in the system file table and you get an fd that points to that file table entry. The file table entry has an integer called the file pointer that indicates the next byte to be read or wriitten in the file. As you read the file, the file pointer gets updated.

When you duplicate an fd by any means such as dup(), fcntrl(), or even fork(), you get new fd's that point to the same file table entry.

If you want two file pointers to the same file, you must have two file table entries in which to store them. That means two open() calls.

Thank you very much.