読み取り専用モードで開かれたファイルが親と子の間でファイルオフセットを共有する理由を理解できませんでした。以下のプログラムはファイル(abcdのようなデータを含む)を開き、次のフォークが呼び出されます。現在、iamは子プロセスと親プロセスの両方でファイルから読み取ろうとしています。ファイルオフセットが出力から共有されていないように見えますか?
# 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 ...