Linux file system

Source: Internet
Author: User

Linux file system is a generalized file system, can be considered that the Linux system for any device and object operation is equivalent to the operation of the file.

The Linux system abstracts all operational objects in a highly abstracted way, which is summed up in the following categories:

1. Ordinary file: It is the narrow concept of the file stored in the disk, is purely the storage of data files, such as text files, picture files, executable files and so on;

2. Character device files: usually refers to the input and output terminal, keyboard, serial port, etc., usually can operate the file mode to operate the character device files, because the reading and writing of such equipment is actually read and write character stream;

3. Block device files: have hard disk, floppy disk and RAM, etc., block device files usually in the public and domestic memory buffer read and write data, support block data read and random read, read and write performance better;

4. Socket file: A file descriptor for network communication, which supports the operation of reading and writing network data like normal files;

Linux provides a virtual file system architecture that requires all devices to provide a consistent file-handling interface that allows users to operate all devices as if they were operating files, so it can be said that all operations are files under the Linux system.

File descriptor

A file descriptor is an abstract identifier for an action file that is used by both user space and the hub of the kernel space. When user space operates on a file descriptor, such as when a file descriptor is being manipulated, when the kernel makes a system call, the corresponding real device is found based on the file descriptor and the result is returned to the user space.

A file descriptor is usually an integer identifier, so it has an on-line value (usually 0-opne_max), depending on the system. So, after we have finished using a file, we should release it as soon as possible (usually called the close function).

1. open files and create files

Header file: Sys/types.h sys/stat.h fcntl.h

int open (const char* filepath, int flags);

int Create (const char* filepath, int flags, mode_t mode);

Open and create successfully returns a file descriptor, failure returns-1. There is usually a limit to the length of the filepath character, which is truncated if the length is exceeded.

Options for Flags:

  O_rdonly (0 Read only)

O_wronly (1 write only)

O_RDWR (2 read and write)  

O_append ( write operation appended to end)

O_create (if the file does not exist, create one and need mode to set permissions)

O_EXCL (see if the file exists.) If O_create is specified and the file already exists, an error is returned)

O_trunc (truncates the file length to 0)

Options for Mode:

S_irwxu user has read and write and Execute permissions

S_IRUSR user has Read access

S_IWUSR User has Write permission

S_IXUSR User has Execute permission

S_IRWXG group users have read-write and Execute permissions

S_IRGRP Group user has Read permission

S_IWGRP group user has write permission

S_IXGRP Group user has execute permission

S_irwxo other users have read and write and Execute permissions

S_iroth other users have read access

S_iwoth other users have write permission

S_ixoth other users have Execute permissions

The operation of the file is blocked by default, that is, you must wait until the file operation returns to continue.

2. Close the file

int close (int fd);

If 0 is returned successfully, the failure returns-1. After the file is closed, the system can use the file descriptor again, and if not closed after use, the process will also close all open file descriptors on exit, but may result in insufficient file descriptors, resulting in the inability to open new files.

3. Reading files

Header file: unistd.h

ssize_t Read (int fd, void* buf, size_t count);

Reads the byte stream of count bytes from the file fd and coexists to the memory address that buf points to. The read succeeded returns the number of bytes read successfully, and if the return 0 identity reads to the end of the file, the read failure returns-1. ssize_t is defined as a dependent platform, possibly a long or an int. The actual number of bytes returned may be less than the size specified by count, indicating that a byte of count size could not be read, and all the bytes currently remaining in the file have been read out.

4. Writing files

Header file: unistd.h

ssize_t Write (int fd, const void* buf, size_t count);

Writes data of the specified count size to the file fd, and the data is from the byte stream in the memory field that buf points to. If the number of successfully written bytes is returned successfully, the failure returns-1.

5. File offset

Header files: sys/types.h unistd.h

off_t lseek (int fd, off_t offset, int whence);

File offset: The current location of the file operation, with all file operations starting at the file offset. If O_append is specified when the file is opened, the file offset is the length of the file, which is the end, otherwise the offset is 0, which is the file start position.

The Lseek function updates the offset of the file fd, which can be either an integer or a negative number, representing the offset size of the relative whence.

Whence options:

  Seek_set: The starting position of the file;

Seek_cur: The current location of the file;

Seek_end: The end position of the file;  

If the function execution succeeds in returning the value of the offset, it may be negative, and the failure returns-1.

When you write data to a file, if you use Lseek to set the offset beyond the file size, when you continue to write data to the file, the intervening white space bytes are populated with '% '.

6. Get File status

Header file Sys/types.h sys/stat.h unistd.h

int stat (const char* path, struct stat* buf);

int fstat (int fd, struct stat* buf);

int Lstat (const char* path, struct stat* buf);

If the fetch succeeds returns 0, the failure returns-1. The data in the file state is written to the data structure that buf points to.

7. File Space Mapping

Header file: Sys/mman.h

void* mmap (void* start, size_t length, int prot, int flags, int fd, off_t offset);

This function maps the file into memory, and then it can take a memory operation, without having to use the read and write functions for better performance.

Start: The starting address of the memory, but usually does not need to be specified, set to NULL, indicating that the system determines the address of the map, reflected in the return value;

Length: The size of the mapped address, that is, the data that is mapped from the file to the memory;

Prot: The protection mode of the map area can be combined by multiple values;

Prot_exec executable Area

Prot_read Readable area

Prot_write Writable Area

Flags: Sets the type of map area, options and whether the map area can be manipulated, can be combined by multiple values;

map_fixed if the address specified by the parameter start cannot be mapped, the mapping fails, usually does not specify the value, the start is set to NULL, and the mapping address is selected by the system;

Map_shared: The mapping area is multi-process shared, the operation of the map area will affect the original file;

Map_private: The write operation of the mapped area will produce a copy, and the write operation will not affect the original file;

Map_denywrite: Write operation to the file is forbidden, only through the operation of the map area to achieve the operation of the file;

Map_locked: Locks the mapped area and is not reset by the virtual memory;

int Munmap (void* start, size_t length);

Cancels the file mapping, usually called after the map area operation is complete, and then closes the file;

1 intFD = open ("Leo.txt", O_RDWR |o_creat, S_irwxu);2         if(FD = =-1) {3printf"create file failed.");4         }5         Else {6                 CharBuf[] ="Leo is me!";7 Write (FD, buf, strlen (BUF));8 9                 Char* ptr = (Char*) mmap (NULL, strlen (buf), Prot_read | Prot_write, map_shared, FD,0);Ten                 if((Char*)-1==ptr) { Oneprintf"Mmap failed."); A                 } -                 Else { -memcpy (PTR,"123",3); the Munmap (PTR, strlen (BUF)); - Close (FD); -                 } -}

8. File attributes operation

Header files: unistd.h fcntl.h

int fcntl (int fd, int cmd);

int fcntl (int fd, int cmd, long arg);

int fcntl (int fd, int cmd, struct flock* lock);

The properties of the file are modified, and the failure returns-1.

Features of the FCNTL:

Copy file descriptor: cmd = F_DUPFD, the return value is a new file descriptor. The new file descriptor is the minimum value in the unused file descriptor that is greater than or equal to the third parameter;

Gets or sets the file descriptor: cmd = F_GETFD/F_SETFD;

Gets or sets the file status value: cmd = F_GETFL/F_SETFL;

File status value:

O_rdonly Read Only

O_wronly Write only

O_rdwr Reading and writing

O_append adding writes to the end

O_nonblock non-blocking mode

O_sync Async Mode

O_async Sync mode

The correct way to obtain o_rdonly,o_wronly and o_rdwr marks is to be obtained with O_accmode and operation;

int fd = open ("Leo.txt", O_RDWR | O_creat, S_irwxu);
if (fd = =-1) {
printf ("Create file failed.");
}
else {
int flags = FCNTL (FD, F_GETFL, 0);
if (Flags < 0) {
printf ("Get flags failed123333.");
}
else {
int accmode = flags & O_accmode;
if (Accmode = = o_rdonly) {
printf ("File only" read.) \ n ");
}
else if (Accmode = = o_wronly) {
printf ("File only write \ n");
}
else if (Accmode = = O_rdwr) {
printf ("file can be read and write. \ n ");
}
Else
{
printf ("Accmode invalid. \ n ");
}

Flags |= o_append;
int result = Fcntl (FD, F_SETFL, &flags);
if (Result < 0) {
printf ("Set file flag failed. \ n ");
}

int newflags = Fcntl (fd, F_GETFL, 0);
if (Newflags & O_append) {
printf ("File append. \ n ");
}
if (Newflags & O_nonblock) {
printf ("File non block. \ n ");
}

Close (FD);
}
}

 Gets or sets the sending object of the file signal: cmd = f_gettown/f_settown/f_getsig/f_setsig;

int // Gets the process ID of the receiving signal Sigio and Sigurg int 10000 // set the process that accepts signals Sigio and Sigurg to a process with ID 10000

Gets or sets the record lock: cmd = f_getlk/f_setlk/f_setlkw;

Gets or sets the file lease: cmd = f_getlease/f_setlease;

9. File input/Output control

Header file: sys/iotl.h

int IOCTL (int device, int request, ...);

By sending commands to the device to control the device, the failure returns-1. Device is an open unit number, and other parameters are determined by the device driver.

#include"stdlib.h"#include"stdio.h"#include<unistd.h>#include<fcntl.h>#include<linux/cdrom.h>#include<sys/ioctl.h>intMainvoid){intFD = open ("/dev/cdrom", O_rdonly |O_nonblock); if(FD >0) {        if(!IOCTL (FD, Cdromeject, NULL)) {printf ("OK \ n"); }        Else{printf ("fail \ n");    }} getchar (); return 0;}

Linux file system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.