Regaring File Table entry

Hi,

I have written following code & ran it on Fedora Linux.
Before executing it I have created a.txt (touch a.txt).

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

int main()
{
    int fd1, rc;

    fd1 = open("a.txt", O_WRONLY);
    if (fd1 == -1)
    {
        printf("Open error\n");
        return -1;
    }
    write(fd1, "ABCD", 4);
    if (fork() > 0)
    {
        write(fd1, "XYZ", 3);
        return 0;
    }
    wait(&rc);
    write(fd1, "EFGH", 4);
    return 0;
}

Why contents of a.txt are "ABCDXYZEFGH"?
More precisely, why kernel had not created separate entry in File Table for child process?
What is the reason behind sharing of File Table entry between parent & child process?
I think as child is independent process. Then if it has written at offset 10 then offset will be incremented to 11 but parent offset should remain at 10 only.

You write "ABCD" to it. Then you write "XYZ" to it. Then you write "EFGH" to it. "ABCD"+"XYZ"+"EFGH" = "ABCDXYZEFGH".

Because the child process didn't open it -- it inherited it. The behavior you've observed is the whole point. Every time you run a command in shell, you're using this property -- the command just writes to its inherited stdout and reads from its inherited stdin and needn't worry about its parent losing sync. This applies to any stream, not just terminals. If you really want them separate, open them separately.

Thank you very much.
If it is shared between parent & child then I think there could be a race condition when both parent & child will try to write/read on it (Am I right?).
If there is then how this has been prevented?

These are system calls, so the kernel itself mediates it. They won't write at the same time, the kernel will impose an order. If they need a specific order, of course, they should be synchronizing themselves via other means. Your code, for instance, synchronizes itself by waiting for the child to finish before writing "EFGH". If the parent instead waited after it wrote, the order wouldn't be guaranteed to be dependable... You might get "EFGH" written first, or you might not.