天天看点

父子进程共享文件表的

通过一段小代码,证明当父进程fork后,并没有复制文件表,只是复制了 文件描述符,所以父子进程

有同样的 状态标识符,当前位移

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <dirent.h>

int main(int argc,char * argv[])

{

        int fd;

        if((fd=open("lhtmpfile",O_RDWR|O_CREAT))<0)

                perror("file open error");

        if(!fork())

        {

                sleep(2);

                printf("child process:%d/n",lseek(fd,0,SEEK_CUR));

                exit(0);

        }

        lseek(fd,20,SEEK_CUR);

        printf("father process:%d/n",lseek(fd,0,SEEK_CUR));

        wait(NULL);

        exit(0);

}

~

~

"fork_filetab.c" 21L, 421C written

$ gcc fork_*

$ ./a.out

father process:20

child process:20

继续阅读