0

我无法理解为什么以只读模式打开的文件会在父子之间共享文件偏移量。下面的程序打开一个文件(其中包含像 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 ...
4

1 回答 1

4

下面的程序打开一个文件(其中包含像 abcd 这样的数据)并调用下一个 fork。

不,它没有。你fork然后打开文件。所以父子分别打开文件,得到单独的打开文件描述。如果您希望他们共享打开的文件描述(包含文件指针),您只需打开文件一次 - 在调用fork.

于 2013-01-12T16:51:28.700 回答