我无法理解为什么以只读模式打开的文件会在父子之间共享文件偏移量。下面的程序打开一个文件(其中包含像 abcd 这样的数据)并调用下一个 fork。现在我正在尝试从子进程和父进程中的文件中读取。看起来文件偏移量没有从输出中共享?
# 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 ...