Linux you need to know basic programming (E)

  1. Linux file-related operations function
    Here Insert Picture Description

    1. function stat, lstat function (penetration function and do not penetrate all functions relative to the soft link)
      1. head File:
        1. #include<sys/types.h>
        2. #include<sys/stat.h>
        3. #include<unistd.h>
      2. Function definition:
        1. Int stat (const * pathname, struct stat * buf); // penetration function (tracking)
        2. Int lstat (const char * pathname, struct stat * buf); // do not penetrate function (without tracking)
      3. Function Description: Get file details
      4. Parameter Description:
        1. Path to the file: Pathname
        2. buf is a pointer to a stat structure
          1. stat structure definition:

             struct stat{
             	dev_t st_dev;     /*ID of device containing file文件的设备编号*/
             	ino_t    st_ino;    /*inode number节点*/
             	mode_t st_mode   /*protection文件的类型和存取权限*/
             	st_mode(这个变量占2byte,共16位)
             		掩码的使用:st_mode & 掩码
             		The following mask values are defined for the file mode component of the st_mode field:
             
             		S_ISUID 04000 set-user-ID bit
             		S_ISGID 02000 set-group-ID bit
             		S_ISVTX 01000 sticky bit
             		
             		S_IRWXU 00700 owner has read,write,and execute permission
             		S_IRUSR 00400 owner has read permission
             		S_IWUSR 00200 owner has write permission
             		S_IXUSR 00100 owner has execute permission
             		
             		S_IRWXG 00070 group has read,write,and execute permission
             		S_IRGRP 00040 group has read permission
             		S_IWGRP 00020 group has write permission
             		S_IXGRP 00010 group has execute permission
             		
             		S_IRWXO 00007 others(not in group) have read,write,and execute permission
             		S_IROTH 00004 others have read permission
             		S_IWOTH 00002 others have write permission
             		S_IXOTH 00001 others have execute permisson
             		
             		S_IFMT 0170000 bit mask for the file type bit field
             		文件类型
             		S_IFSOCK 0140000 socket
             		S_IFLNK 0120000 symbolic link(符号链接)
             		S_IFREG 0100000 regular file
             		S_IFBLK 0060000 block device
             		S_IFDIR 0040000 directory
             		S_IFCHR 0020000 character device
             		S_IFIFO 0010000 FIFO
             	Nlink_t st_nlink   /*number of hard links硬链接数目*/
             	Uid_t st_uid  /*user ID of owner用户ID*/
             	Gid_t st_gid  /*group ID of owner组ID*/
             	Dev_t st_rdev  /*device id (if special file)*/
             	Off_t st_size  /*total size,in bytes文件字节数*/
             	Blksize_t st_blksize  /*blocksize for filesystem I/O块大小*/
             	Blkcnt_t st_blocks  /*number of 512B blocks allocated分配512B的数目*/
             	
             	/*since linux 2.6, the kernel supports nanosecond precison for the following timestamp fields.自从linux2.6,内核支持十亿分之一秒的精确度对于下面的时间戳字段*/
             	Struct timespec st_atim  /*time of last access*/
             	Struct timespec st_mtim  /*time of last modification*/
             	Struct timespec st_ctim  /*time if last status change*/
             	
             #define st_atime st_aim.tv_sec /*backward compatibility向下兼容*/
             #define st_mtime st_mtim.tv_sec 
             #define st_ctime st_ctim.tv_sec
             };
            
      5. 函数返回值:
        on success,zero is returned.on error, -1 is returned, and errno is set approriately.
    2. access function
      1. Role: test specified file if there is some kind of authority
      2. prototype:
        1. Int access(const char *pathname,int mode)

        2. parameter:

           a) pathname:文件名
           b) mode:权限类别
           	i) R_OK是否有读权限
           	ii) W_OK是否有写权限
           	iii) X_OK是否有执行权限
           	iv) F_Ok测试一个文件是否存在
           	v) F_OK tests for the existence of the file.R_OK,W_OK,and X_OK test whether the file exists and grants read,write,and execute permissions,respectively.
          
        3. Return Value:
          A) 0 - >> Check all rights have to be checked by
          b) -1 - >> have permission is prohibited

    3. chmod function
      1. Header:
        #include <SYS / defined in stat.h>
      2. Function definition:
        int chmod (const char * pathname, mode_t the MODE)
      3. 函数描述:
        chmod() changes the permissions of the file specified whose pathname is given in pathname,which is dereferenced if it is a symbolic link(符号链接)
      4. Parameter Description
        1. Path to the file: pathname
        2. mode: permission settings
      5. 函数返回值:
        on success,zero is returned.on error,-1 is returned,and errno is set appropriately
    4. chown function
      1. Header file:
        #include <unistd.h>
      2. 函数定义:
        int chown(const char *pathname,uid_t owner,gid_t group)
        int fchown(int fd,uid_t owner,gid_t group)
        int lchown(const char * pathname,uid_t owner,gid_t group)
      3. 函数描述:
        These system calls changes the owner and group of a file. The chown(),fchown(),and lchown() system calls differ only in how file is specified:
        1. chown() changes the ownership of the file specified by pathname,which is dereferenced if it is a symbolic link
        2. fchown() changes the ownership of the file refered to by the open file descriptor fd
        3. lchown() is like chown().but dose not dereference symbolic links
      4. Function parameters:
        1. pathname: refers to the path to the file
        2. owner: user id
        3. group: group id
      5. 函数返回值:
        on success,zero is returned. on error,-1 is returned,and errno is set appropriately
    5. truncate function
      1. head File:
        1. #include<unistd.h>
        2. #include<sys/types.h>
      2. Function definition:
        1. int truncate(const char * path,off_t length)
        2. int ftruncate(int fd,off_t length)
      3. Function Description:
        1. the truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
        2. if the file previously was largerly than this size, the extra data is lost.if the file previous was shorter, it is extended,and the extend part read as null bytes("\0")
        3. the file offset is not changed
        4. if the size changed,then the st_ctime and st_mtime fields(respectively,time of last status change and time of last modification;see stat(2)) for the file are updated,and the set-user-id and set-group-id mode bits may be cleared.
        5. with ftruncate(),the file must be open for writing;with truncate(),the file must be writable.
      4. Function parameters:
        1. path: file path
        2. length: the size of the file needs to be adjusted
          1. length is greater than the file size, the file will later fill in empty bytes or air-conditioning
          2. length is less than the file size, file extra part, will be discarded
      5. 函数返回值:
        on success ,zero is returned.on error,-1 is returned,and errno is set appropriately
    6. Link function
      1. link function
        1. Header file:
          #include <unistd.h>
        2. Function definition:
          int Link (const char * oldpath, const char * newpath is)
        3. Function Description:
          1. link() create a new link (also known as a hard link) to an existing file
          2. if newpath exists, it will not overwritten
          3. this new name may be used exactly as the old one for any operation;both names refer to the same file(and so have the same permissions and ownership) and it is impossible to tell which name was the “original”
        4. Function parameters:
          1. oldpath: the old path of the file
          2. Path of the new file: newpath
        5. 函数返回值:
          on success, zero is returned.on error ,-1 is returned , and errno is set appropriately
      2. symlink function
        1. Header file:
          #include <unistd.h>
        2. Function definition:
          int symlink (const char * target, const char * linkpath)
        3. 函数描述:
          symlink creates a symbolic link named linkpath which contains the string target.
        4. Function parameters:
          1. target: the target object
          2. linkpath: Create a soft path connected
        5. 函数返回值:
          on success, zero is returned.on error ,-1 is returned , and errno is set appropriately
      3. readlink function (read only soft links)
        1. Header file:
          #include <unistd.h>
        2. Function definition:
          ssize_t readlink (pathname const char *, char * buf, size_t BUFSIZ)
        3. 函数描述:
          readlink() places the contents of the symbolic link pathname in the buffer buf,which has size bufsiz. readlink() does not append a null byte to buf. It will truncate the contents(to a length of bufsiz characters),in case the buffer is too small to hold all of the contents
        4. Function parameters:
          1. Pathname of the file: pathname
          2. buf: Buffer
          3. bufsiz: Buffer Size
        5. 函数返回值:
          on success, these calls return the number of bytes placed in buf. on error,-1 is returned and errno is set to indicate the error
      4. unlink function
        1. Header file:
          #include <unistd.h>
        2. Function definition:
          int unlink (const char * pathname)
        3. Function Description:
          1. unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.
          2. If the name was the last link to a file but any process still have the file open , the file will remain in existence until the last file descriptor referring to it is closed
          3. If the name refered to a symbolic link, the link is removed.
          4. If the name refered to a socket ,FIFO , or device , the name for it is removed but processes which have the object open may continue to use it
        4. Function parameters:
          path to the file: pathname
        5. 函数返回值:
          on success, zero is returned.on error , -1 is returned, and errno is set appropriately
    7. rename function
      1. Header file:
        #include <stdio.h>
      2. Function definition:
        int the rename (const char * oldpath, const char * newpath)
      3. Function Description:
        1. rename() renames a file,moving it between directories if required. Any other hard links to the file (as created using link(2)) are unaffected. Open file descriptor for oldpath are also unaffected.
        2. If newpath already exists, it will be atomically replaced replaced (subject to a few conditions; see ERRORS below), so that there is no point at which another process attempting to access newpath will find it missing.
        3. If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.
        4. If newpath exists but operation fails for some reason, rename() guarantees to leave an instance if newpath in place
        5. oldpath can specify a directory. In this case, newpath must either not exist, or it must specify an empty directory.
        6. However, when overwriting there will probably be a window in which both oldpath and newpath refer to the file being renamed.
        7. If oldpath refers to a symbolic link, the link is renamed; if newpath refers to a symbolic link, the link will be overwritten.
      4. Function parameters:
        1. oldpath: source file path
        2. newpath: New file path
      5. 函数返回值:
        on success, zero is returned. on error , -1 is returned , and errno is set appropriately.
  2. Linux directory operations related functions

    1. chdir function
      1. Header file:
        #include <unistd.h>
      2. Function Prototype:
        int the chdir (const char * path);
      3. 函数描述:
        chdir() changes the current working directory of the calling process to the directory specified in path
      4. Function parameters:
        1. Path to the file: path
      5. Function return value:
        1. on success,zero is returned. on error, -1 is returned, and errno is set approproately
    2. getcwd function
      1. Header file:
        #include <unistd.h>
      2. Prototype:
        1. char * getcwd(char * buf, size_t size);
        2. char * getwd(char * buf);
      3. Function Description:
        get working directory of the current process
      4. Function parameters:
        1. buf: Buffer
        2. size: buffer size
      5. Function return value:
        1. on success, these functions return a pointer to a string containing the pathname of the current working directory. In the case getcwd() and getwd() this is the same value as buf
        2. on failure, these functions return null, and errno is set to indicate the error. The contents of the array pointed to by buf are undefined on error.
    3. mkdir function
      1. head File:
        1. #include<sys/stat.h>
        2. #include<sys/types.h>
      2. Function prototype:
        int mkdir (const char * pathname, mode_t the MODE)
      3. Function Description:
        1. mkdir() attempts to create a directory named pathname
        2. The argument mode specifies the mode for the new directory. It is modified by the process’s umask in the usual way: in the absence of a default ACL, the mode of the created directory is (mode & ~umask & 0777). Whether other mode bits are honored for the created directory depends on the operating system.
      4. Function parameters:
        1. Path to the directory: Pathname
        2. Directory permissions: Mode
      5. 函数返回值:
        mkdir() return zero on success, or -1 if an error occurred (in which case,errno is set appropriately)
    4. rmdir function
      1. Header file:
        #include <unistd.h>
      2. Function prototype:
        int rmdir (const char * pathname)
      3. Function Description:
        rmdir () Deletes A Directory, Which MUST BE empty.
      4. Function parameters:
        path to the directory: pathname
      5. 函数返回值:
        On success, zero is returned. On error, -1 is returned, and errno is set approproately.
    5. opendir function
      1. head File:
        1. #include<sys/types.h>
        2. #include<dirent.h>
      2. Function prototype:
        the DIR * the opendir (const char * name);
      3. 函数描述:
        The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory.
      4. Function parameters:
        the name of the file: mame
      5. 函数的返回值:
        The opendir() functions return a pointer to the directory stream. On error, NULL is returned, and errno is set appropriately.
    6. readdir function
      1. Header file:
        #include <dirent.h>

      2. Function prototype:
        struct dirent * readdir (DIR * dirp)

      3. Function Description:

        1. The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dirp. It returns null on reaching the end of the directory stream or if an error occurred.

        2. on Linux, the dirent structure is defined as follow:

           struct dirent{
           	ino_t d_ino;/*inode number*/
           	off_t d_off;/*not an offset*/
           	unsigned short d_reclen;/*length of this record*/
           	unsigned char d_type;/*type of file*/
           	char d_name[256];/*filename*/
           };
          
      4. Function parameters:
        dirp: directory pointer

      5. 函数的返回值:
        on success , readdir() returns a pointer to a dirent structure.if the end of the directory stream is reached, NULL is returned and errno is not changed. If an errno occurs, NULL is returned and errno is set appropriately

    7. closedir function
      1. head File:
        1. #include<sys/types.h>
        2. #include<dirent.h>
      2. Prototype:
        1. Int closedir(DIR * dirp);
          3 函数描述:
          The close() function closes the directory stream associated with dirp. A successful call to closedir() also closes the underlying file descriptor associated with drip. The directory stream descriptor dirp is not available after this call.
      3. Function parameters:
        dirp: directory pointer
      4. 函数返回值:
        The closedir() function returns 0 on success. On error, -1 is returned, and errno is set appropriately.
  3. fcntl function
    attribute change file is already open files and processes

  4. dup, dup2 function

    1. Header file:
      #include <unistd.h>
    2. Prototype:
      1. Int dup(int oldfd);
      2. Int dup2(int oldfd,int newfd);
    3. Function Description:
      1. The dup() system call creates a copy of the file descriptor oldfd,using the lowest-numbered unused descriptor for the new descriptor.
      2. After a successful return, the old and new file descriptors may be used interchangeably. They refer to the same open file description and thus share file offset and file status flags; for example , if the file offset is modified by using lseek() on one of the descriptors, the offset is also changed for the other.
      3. The dup2() system call performs the same task as dup(), but instead of using the lowest-numbered unused file descriptor, it uses the descriptor number specified in newfd. If the descriptor newfd was previously open, it is silently closed before being reused.
      4. The steps if closing and reusing the file descriptor newfd are performed atomically. This is important, because trying to implement equivalent functionality using close() and dup() would be subject to race conditions, whereby newfd might be reused between the two steps. Such reuse coulld happen because the main program is interrupted by a signal handler that allocates a file descriptor, or because a parallel thread allocates a file descriptor.
      5. note the following points:
        1. If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.
        2. If oldfd is a valid file descriptor, and newfd has the same values as oldfd, the dup2() does nothing, and returns newfd.
    4. Function parameters:
      . 1) oldfd: old file descriptor according to
      2) newfd: new file descriptor
    5. 函数返回值:
      on success, these system calls return the new descriptor. on error, -1 is returned, and errno is set appropriately.
  5. Inode

    1. Inode inode: actually saved some real information data, the information to be "metadata" (that is, an overview of the file attributes). For example: time stamp file size, the device identifier, a user group identifier, file mode, extended attributes, read or modified the file, the number of links, pointers to the contents of disk storage blocks, file classification, etc.
      (Note that the data is divided into: the data itself metadata +)

    2. Note how the inode is generated: the size of each of the inode, typically 128 bytes or 256 bytes. The total number of the inode is, when formatting for a given (now OS can change dynamically), generally provided on a 2KB inode. Usually file system file rarely less than 2KB, according to predetermined so 2KB points, generally inode is used up. So innode when the file system is installed there will be a default number, the latter will change according to actual needs.

    3. Note innode number: innode number is unique, it represents a different file. In fact, when the inside of Linux, access files are carried out by inode number, called the file name just to give users easy to use. When we open a file, first of all, the system finds the inode number corresponding to the file name; then, by innode number, get inode information, and finally, have found inode file data block is located, can now handle the data file.

    4. Relations inode and file: When creating a file, give the file is assigned a innode. An inode corresponds to only one actual file, a file will be only one inode. The maximum number of inodes is the maximum number of files


The following is the author of the micro-channel public number, welcome attention, will continue to update c ++, python, tensorflow, machine learning, deep learning, computer vision and other articles, public No. contains 300+ this pdf e-books, certainly you need one, you can receive public attention No. Oh.
Here Insert Picture Description
If you are interested in JAVA aspects, can focus on the following JAVAERS public number, accompany you learn together, grow together, sharing poetry and distant JAVA road together. In which public numbers are JAVA friend of this world, the public will have number-technical articles every day, by dry surface, but also the advanced architecture of e-books, such as Spring combat, SpringBoot practical, high-performance MySQL, in-depth understanding of JVM, RabbitMQ combat , Redis design and implementation of a number of high-quality books and so on, you can receive public attention No. Oh.
Here Insert Picture Description

Published 46 original articles · won 187 Like · views 20000 +

Guess you like

Origin blog.csdn.net/Xiao_Jie123/article/details/105323955