一步一步粗谈linux文件系统(五)----关于fork,文件系统在各个进程中

来源:互联网 发布:php网站源代码 编辑:程序博客网 时间:2024/06/04 19:41

关于fork,我们都知道fork出新的进程,会复制旧进程的所有资源,且堆栈、数据不共享。所以关于文件系统,要是不共享,会出现怎么样的情况呢?就是说各个进程都有自己的文件系统copy,那种感觉不敢想象,所以他们一定是资源共享的,一定是同步的。

fork新进程的操作中,其中

static structtask_struct *copy_process(unsigned long clone_flags,

unsignedlong stack_start,

structpt_regs *regs,

unsignedlong stack_size,

int__user *parent_tidptr,

int__user *child_tidptr,

intpid)

中调用了

if ((retval =copy_fs(clone_flags,p)))        //文件下系统copy

gotobad_fork_cleanup_files;

最终调用了

static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old){struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL);//fs分配一块内存区域/* We don't need to lock fs - think why ;-) */if (fs) {atomic_set(&fs->count, 1);rwlock_init(&fs->lock);fs->umask = old->umask;read_lock(&old->lock);fs->rootmnt = mntget(old->rootmnt);fs->root = dget(old->root);fs->pwdmnt = mntget(old->pwdmnt);fs->pwd = dget(old->pwd);if (old->altroot) {fs->altrootmnt = mntget(old->altrootmnt);fs->altroot = dget(old->altroot);} else {fs->altrootmnt = NULL;fs->altroot = NULL;}read_unlock(&old->lock);}return fs;}

亮点在哪?指针!struct fs_struct *fs;你没有看错,就是这个指针,再结合下面的代码,可以得出,fork出来新的文件系统指针指向于旧的那一块指向的。那意味着,后面不管是那个进程的task->fs其实都是进程0创建出来的fs,即前面一篇中所提到的rootfs,所以各个进程间的文件系统是资源共享的,同步的。