您的位置:首页 > 运维架构 > Linux

Linux文件系统

2015-08-09 20:58 597 查看
chdir("/a");//改变当前进程的目录

chdir("b");

open("c", O_RDONLY);//打开/a/b 目录下的c文件

open("/a/b/c", O_RDONLY);//这个函数同上面的达到的目的一样

创建目录或者文件的三种方式

mkdir("/dir");//创建目录

fd = open("/dir/file", O_CREATE|O_WRONLY);//创建文件 如果有就读取 没有就创建

close(fd);

mknod("/console", 1, 1);//创建设备文件

Mknod creates a file in the file system, but the file has no contents. Instead, the file’s

metadata marks it as a device file and records the major and minor device numbers

(the two arguments to mknod), which uniquely identify a kernel device.

When a process later opens the file, the kernel diverts read and write system calls to the kernel

device implementation instead of passing them to the file system.

文件状态defined in stat.h as:

#define T_DIR 1 // Directory

#define T_FILE 2 // File

#define T_DEV 3 // Device

struct stat {

    short type;  // Type of file

    int dev;  // File system’s disk device

    uint ino;  // Inode number

    short nlink; // Number of links to file

    uint size;  // Size of file in bytes

};

文件被叫做索引,一个文件可以有多个名字被称为链接

open("a", O_CREATE|O_WRONLY);//创建一个文件a

link("a", "b");//文件a也可以叫做文件b

对文件a的读写等同于对文件b的读写。

每一个文件都有特定索引号,但是可以有不同的连接。上面的两个a,b文件

文件状态fstat 有相同的ino索引号,但是nlink为2.

unlink将删除一个文件的名字,当文件状态stat nlink=0的时候,并且没有文件描述符表示它的时候

才会删除硬盘上的空间。

unlink("a")仅仅删除该索引的一个名字,也就是该文件的一个名字,它还是可以通过b去访问的。

fd = open("/tmp/xyz", O_CREATE|O_RDWR);

unlink("/tmp/xyz");

这是一种经常用来创建临时索引(文件)的方法,当进程关闭fd 或者进程退出的时候.这个索引就会

被清除。

文件操作系统是作为用户等级的程序设计的,这种设计可以允许用户去扩展shell,设置新的用户命令

cd命令是一个例外,它被写进了内核程序,cd命令是改变shell当前的工作目录。如果cd作为用户程序

作为常规命令,shell创建一个子进程,子进程中运行cd命令,那么子进程的工作目录将会改变,父进程的目录则

不会改变。

shell cd内核程序如下:

// Read and run input commands.

8515     while(getcmd(buf, sizeof(buf)) >= 0){

8516         if(buf[0] == ’c’ && buf[1] == ’d’ && buf[2] == ’ ’){

8517             // Clumsy but will have to do for now.

8518             // Chdir has no effect on the parent if run in the child.在子进程中运行Chdir对父进程没有影响。

8519             buf[strlen(buf)-1] = 0; // chop \n

8520             if(chdir(buf+3) < 0)

8521                 printf(2, "cannot cd %s\n", buf+3);

8522             continue;

8523          }

8524     if(fork1() == 0)

8525         runcmd(parsecmd(buf));

8526         wait();

8527     }

8528         exit();

8529     读取shell中的命令,如果命令是cd 则直接运行chdir()函数,如果命令不是cd的话,

            则创建子进程利用runcmd()函数去执行这个命令,父进程等待子进程执行完。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: