Chinaunix首页 | 论坛 | 博客
  • 博客访问: 569043
  • 博文数量: 137
  • 博客积分: 4040
  • 博客等级: 上校
  • 技术积分: 1584
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-08 13:05
文章分类

全部博文(137)

文章存档

2011年(10)

2010年(23)

2009年(104)

分类: LINUX

2009-08-19 15:19:29

/*
 * linux/fs/fcntl.c
 *
 * (C) 1991 Linus Torvalds
 */


#include <string.h>
#include <errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <asm/segment.h>

#include <fcntl.h>
#include <sys/stat.h>

extern int sys_close(int fd);// 关闭文件系统调用


static int dupfd(unsigned int fd, unsigned int arg)// 复制文件句柄(描述符)

{
    if (fd >= NR_OPEN || !current->filp[fd])// 如果文件句柄值大于一个程序最多打开文件数NR_OPEN,或者该句柄的文件结构不存在,则出错

        return -EBADF;
    if (arg >= NR_OPEN)// 如果指定的新句柄值arg 大于最多打开文件数,则出错

        return -EINVAL;
    while (arg < NR_OPEN)// 在当前进程的文件结构指针数组中寻找索引号大于等于arg 但还没有使用的项

        if (current->filp[arg])
            arg++;
        else
            break;
    if (arg >= NR_OPEN)// 如果找到的新句柄值arg 大于最多打开文件数,则出错,返回出错码并退出

        return -EMFILE;
    current->close_on_exec &= ~(1<<arg);// 在执行时关闭标志位图中复位该句柄位。也即在运行exec()类函数时不关闭该句柄

    (current->filp[arg] = current->filp[fd])->f_count++;//复制,且引用数加1

    return arg;//返回新的文件句柄

}

int sys_dup2(unsigned int oldfd, unsigned int newfd)// 复制文件句柄系统调用函数

{
    sys_close(newfd);//先关闭新句柄

    return dupfd(oldfd,newfd);// 复制文件句柄(描述符)

}

int sys_dup(unsigned int fildes)// 复制文件句柄系统调用函数

{// 复制指定文件句柄fildes,新句柄的值是当前最小的未用句柄

    return dupfd(fildes,0);// 复制文件句柄(描述符)

}

int sys_fcntl(unsigned int fd, unsigned int cmd, unsigned long arg)// 文件控制系统调用函数

{    
    struct file * filp;

    if (fd >= NR_OPEN || !(filp = current->filp[fd]))// 如果文件句柄值大于一个进程最多打开文件数NR_OPEN,或者该句柄的文件结构指针为空,则出错

        return -EBADF;
    switch (cmd) {
        case F_DUPFD:// 复制文件句柄

            return dupfd(fd,arg);
        case F_GETFD:// 取文件句柄的执行时关闭标志

            return (current->close_on_exec>>fd)&1;
        case F_SETFD:// 设置句柄执行时关闭标志。arg 位0 置位是设置,否则关闭

            if (arg&1)
                current->close_on_exec |= (1<<fd);
            else
                current->close_on_exec &= ~(1<<fd);
            return 0;
        case F_GETFL:// 取文件状态标志和访问模式

            return filp->f_flags;
        case F_SETFL:// 设置文件状态和访问模式(根据arg 设置添加、非阻塞标志)

            filp->f_flags &= ~(O_APPEND | O_NONBLOCK);
            filp->f_flags |= arg & (O_APPEND | O_NONBLOCK);
            return 0;
        case F_GETLK:    case F_SETLK:    case F_SETLKW:
            return -1;
        default:
            return -1;
    }
}

阅读(971) | 评论(0) | 转发(0) |
0

上一篇:stat.c

下一篇:ioctl.c

给主人留下些什么吧!~~