天天看點

父子程序共享檔案表的

通過一段小代碼,證明當父程序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

繼續閱讀