我们在这篇博客中主要讨论三个知识点:分别是atexit(),Linux中的粘滞位和FILE结构体。
一、验证连续注册三个函数,看输出顺序(atexit)
源码:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
void fun()
{
printf("hello fun\n");
return;
}
void fun1()
{
printf("hello fun1\n");
return;
}
void fun2()
{
printf("hello fun2\n");
return;
}
int main()
{
atexit(fun);
atexit(fun1);
atexit(fun2);
printf("hello main\n");
sleep(5);
return 0;
}
输出结果:
从上面的结果可以看出, 进程退出时,系统会自动调用atexit初始回调函数(参数函数),但多次调用时的输出顺序是逆序的。
二、粘滞位
粘滞位(Sticky bit),或粘着位,是Unix文件系统权限的一个旗标。最常见的用法在目录上设置粘滞位,如此以来,只有目录内文件的所有者或者root才可以删除或移动该文件。如果不为目录设置粘滞位,任何具有该目录写和执行权限的用户都可以删除和移动其中的文件。实际应用中,粘滞位一般用于/tmp目录,以防止普通用户删除或移动其他用户的文件。
三、FILE结构体
struct file结构体定义在include/Linux/fs.h中定义。文件结构体代表一个打开的文件,系统中的每个打开的文件在内核空间都有一个关联的 struct file。它由内核在打开文件时创建,并传递给在文件上进行操作的任何函数。在文件的所有实例都关闭后,内核释放这个数据结构。在内核创建和驱动源码中,struct file的指针通常被命名为file或filp。如下所示:
struct file {
union {
struct list_head fu_list; //文件对象链表指针linux/include/linux/list.h
struct rcu_head fu_rcuhead; //RCU(Read-Copy Update)是Linux 2.6内核中新的锁机制(详细了解http://www.ibm.com/developerworks/cn/linux/l-rcu/)
} f_u;
struct path f_path; //包含dentry和mnt两个成员,用于确定文件路径
#define f_dentry f_path.dentry //f_path的成员之一,当前文件的dentry结构
#define f_vfsmnt f_path.mnt //表示当前文件所在文件系统的挂载根目录
const struct file_operations *f_op; //与该文件相关联的操作函数
atomic_t f_count; //文件的引用计数(有多少进程打开该文件)
unsigned int f_flags; //对应于open时指定的flag
mode_t f_mode; //读写模式:open的mod_t mode参数
loff_t f_pos;//当前文件指针位置
off_t f_pos; //该文件在当前进程中的文件偏移量
struct fown_struct f_owner; //该结构的作用是通过信号进行I/O时间通知的数据。
unsigned int f_uid, f_gid;// 文件所有者id,所有者组id
struct file_ra_state f_ra; //在linux/include/linux/fs.h中定义,文件预读相关
unsigned long f_version;//记录文件的版本号,每次使用之后递增
#ifdef CONFIG_SECURITY
void *f_security;
#endif
/* needed for tty driver, and maybe others */
void *private_data;//使用这个成员来指向分配的数据
#ifdef CONFIG_EPOLL
/* Used by fs/eventpoll.c to link all the hooks to this file */
struct list_head f_ep_links;
spinlock_t f_ep_lock;
#endif /* #ifdef CONFIG_EPOLL */
struct address_space *f_mapping;
};