Gowtam
Gowtam

Reputation: 505

When the file is opened in readonly mode, does parent and child share the same file offset after fork?

I couldn't able understand why a file opened in the readonly mode dosent share the file offset between parent and child. Below program openes a file ( which contains data like abcd ) and next fork is called. Now iam trying to read from file in both child and parent process. Looks like file offset is not shared from the output ?.

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

# define CHILD 0

main(){
int fd;
char buf[4];
pid_t pid;  
int childstatus;
    pid = fork();   
fd = open("./test",O_RDONLY);
if( pid == CHILD){
    printf("Child process start ...\n");
    read(fd,buf,2);
    printf(" in child %c\n",buf[0]);
    read(fd,buf,2);
    printf(" in child %c\n",buf[0]);
    sleep(5);
           printf("Child terminating ...\n");
}
// parent
else{    
        printf("In parent  ...\n");     
    sleep(3);
    read(fd,buf,2);
    printf(" in parent %c\n",buf[0]);
    close(fd);
    sleep(5);
           printf("parent terminating ...\n");
}

}

Output :

In parent  ...
Child process start ...
 in child a
 in child c
 in parent a
Child terminating ...
parent terminating ...

Upvotes: 0

Views: 204

Answers (1)

David Schwartz
David Schwartz

Reputation: 182855

Below program openes a file ( which contains data like abcd ) and next fork is called.

No, it doesn't. You fork and then open the file. So the parent and child open the file separately and get separate open file descriptions. If you want them to share an open file description (which holds the file pointer), you have to open the file only once -- before calling fork.

Upvotes: 4

Related Questions