Details Linux file Programming __HTML5

Source: Internet
Author: User
Tags anonymous function prototype lstat file permissions

As you all know, under Linux, everything is file, so familiar with Linux file operation, Linux is the basis for programming. Cut the crap, get into the subject.

In Linux, the file descriptor is used to represent the common file of the device file, the file descriptor is an integer data, and all operations on the file are implemented by the file descriptor.

File descriptors are hubs for connecting user space and kernel space in file systems, and when we open one or create a file, the kernel space creates the corresponding structure and

A variable of an integer is passed to the corresponding process of the user space, and the process uses the file descriptor to manipulate the file. Note that the file descriptor is a limited

Resources, so you should release them in time after use, typically by calling the close () function. There are 3 file descriptors in the Linux system that are already allocated, and that is the standard

Input, standard output and standard error, their file descriptors are 0,1,2.

1.open (), create () function

Under Linux, the Open () function is used to open an existing file or to create a new file, and the Create () function is used to create a new file:

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

int open (const char *pathname,int flags,mode_t mode);

Where flags set the standard for the user, the possible values are: o_rdonly (read only), O_wronly (write only), O_RDWR (read-write), O_append (append)

O_creat (not created) wait, here's the oppression. The special note is that when we select O_creat, we want to set the new file permissions in the Mode argument.

Pathname as file path

The mode parameter is used to indicate permission to open a file, and it must be used in conjunction with the o_creat of flags.

int Create (const char *parhname,mode_t mode);

The CREATE function is equivalent to the abbreviated version of Open: Open (parhname,o_wronly| O_creat| O_trunc,mode);

2. Reading the file read function

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

The read function is the buffer that is responsible for reading the count byte content from FD and placing it in the BUF. When read successfully, the corresponding reading position pointer of the file moves back to the position, and the size of the

The number of bytes successfully read, read returns the number of bytes actually read, if the value returned is 0 indicating that the file has been read to the end, less than 0 indicates an error occurred.

3. Write file writing () function

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

The Write function writes the count byte content in buf to the file descriptor FD. Returns the number of bytes written when successful. Returns-1 on failure. and set the errno variable.

4 file Offset function Lseek ()

Each open file has a "current file offset" associated with it. Typically, both the read and write operations start at the current file offset and the offset increases the number of bytes read and written.

By default, when a file is opened, the offset is set to 0 unless you specify the O_append option. You can call Lseek to explicitly set an open file

The offset is placed. #include <unistd.h> off_t lseek (int filedes, off_t offset, int whence);

Return value: Successful return of the new file offset, error return-1. The interpretation of parameter offset is related to the value of the parameter whence. If Seek_set, the offset of the file is set to offset bytes from the beginning of the file. If seek_cur, the offset of the file is set to the current value plus offset,offset can be positive or negative. If seek_end, the file's offset is set to the file length plus offset,offset can be positive or negative.

You can determine the current offset of an open file in the following ways: off_t Currpos; Currpos = Lseek (FD, 0, seek_cur);

This approach can also be used to determine whether the file involved can set an offset. If the file descriptor refers to a pipe, FIFO, or network socket, Lseek returns-1 and

Errno is set to Espipe. Typically, the current offset of a file should be a non-negative integer, but some devices may also allow negative offsets. But for normal files, the offset

Quantity must be non-negative. Because the offset may be negative, all should be cautious when comparing the Lseek return value, not to test whether it is less than 0, and to test whether it equals-1.

Lseek only records the current file offset in the kernel, it does not cause any I/O operations.

The file offset can be greater than the current length of the file, in which case the next write to the file will be lengthened and an empty file is formed. is in the file but not

All the bytes written are read as 0. The holes in the file do not require storage to be occupied on disk.

5. Get file status Fstat () function

#include <sys/stat.h>

int stat (const char*pathname,struct STAT*BUF);
int fstat (int filedes,struct stat*buf);
int Lstat (const char *pathname,struct stat*buf);

The return of these three functions: if the success is 0, the error is-1. Give a pathname,stat function to return an information structure related to this named file, the Fstat function obtained

Information about a file that has been opened on the descriptor filedes. The Lstat function is similar to stat, but when a named file is a symbolic connection, the Lstat returns the symbol connection

Information, not the file referenced by the symbol connection.

The second argument is a pointer to a structure that we should provide. These functions fill in the structure pointed to by BUF. The actual definition of the structure may be implemented differently, but its basic form is:

struct stat{
Mode St_mode; /* File type and mode (license number) * *
Ino st_ino;/* I-node number (serial number) * *
Dev st_dev;/* Equipment Number (file system) */
Dev st_rdev;/* device number for special file * *
Nlink st_nlink;/* Connection Number * *
UID st_uid;/* owner's user id*/
GID st_gid;/* Group id*/
Off st_size;/* byte length of normal file * *
Time st_atime;/* Last access times * *
Time st_mtime;/* last modified access times * *
Time st_ctime;/* last file state changed *
Long st_blksize;/* best I/O block length * *
512-byte block number allocated by long st_blocks;/*
};

6. File space mapping Mmap () function

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

There are three main uses for this function:
1, mapping a common file into memory, usually in need of files frequently read and write to use, so that memory read and write instead of I/O read and write, to achieve higher performance;
2. Anonymous memory mapping of special files can provide shared memory space for the associated process;
3. Provides shared memory space for unrelated processes and typically maps a normal file to memory.

Mmap system calls enable shared memory to be realized by mapping the same common file between processes. After the normal file is mapped to the process address space, the process can access the file as normal memory

Without having to call read (), write (), and so on.

Parameter start: Point to the memory start address to map, usually set to NULL, to allow the system to automatically select the address, and the mapping succeeds to return the address.

Parameter length: Represents how large portions of a file are mapped to memory.

Parameter prot: How the mapped area is protected. There are several ways to combine the following:
Prot_exec map area can be executed
Prot_read map area can be read
Prot_write map area can be written
Prot_none map area cannot be accessed

Parameter flags: various attributes that affect the mapped region. You must specify map_shared or map_private when calling Mmap ().
Map_fixed if the address that the parameter start refers to cannot successfully establish a mapping, the mapping is discarded and the address is not modified. This flag is usually discouraged.
Map_shared writes data to the mapped region is copied back into the file and allows other processes that map the file to share.
Map_private writes to a mapped region produces a copy of the mapping file, that is, any changes made to this area by the private write-time copy (copy on write) will not be written

Back to the original file contents.
Map_anonymous establishes an anonymous mapping. The parameter FD is ignored, the file is not involved, and the mapped zone cannot be shared with other processes.
Map_denywrite only allows writes to the mapped region, and other operations that write directly to the file will be rejected.
Map_locked the mapped area, which means that the area will not be replaced (swap).

Parameter FD: The file descriptor to map to in memory. If you are using an anonymous memory map, the MAP_ANONYMOUS,FD setting is set to-1 in flags. Some systems do not support anonymous memory

Mapping, you can use fopen to open a/dev/zero file and then map the file to the same effect as an anonymous memory map.

Parameter offset: The offset of the file map, usually set to 0, representing the beginning of the front of the file, offset must be an integer multiple of the paging size.

return value:

If the mapping succeeds, return the memory start address of the mapping area, otherwise return map_failed (-1), and the reason for the error is stored in the errno.

The system calls Mmap () for shared memory in two ways:

(1) Memory maps provided using normal files:

Apply to any process. At this point, you need to open or create a file, and then call Mmap ()

The typical calling code is as follows:

Fd=open (name, flag, mode);

if (fd<0)

.........

Ptr=mmap (NULL, Len, prot_read| Prot_write, map_shared, FD, 0);

..........

Munmap (Ptr,len);

Close (FD);

When you have finished working on the file, you need to use the Munmap () function to cancel the address of the mmap () map and close the open file.

(2) using special files to provide anonymous memory mappings:

Applies to relationships between processes. Because of the special affinity of the parent-child process, mmap () is called first in the parent process, and then the fork () is invoked. Then after calling fork (),

The child process inherits the address space of the parent process's anonymous mapping and also inherits the address returned by Mmap (), so that the parent-child process can communicate through the mapped zone. Attention, here.

is not a general inheritance relationship. In general, a child process maintains a separate number of variables inherited from the parent process. The address returned by Mmap () is maintained jointly by the parent-child process. For tools

The best way for a relational process to implement shared memory is by using an anonymous memory map. At this point, you do not have to specify a specific file, just set the appropriate flag

7. File attribute Fcntl () function

The Fcntl () function sends a command to the open file FD to change its properties. The function prototype is as follows:

#include <unistd.h>
#include <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);

Operation succeeded, its return value depends on CMD, error return-1. The following command has a special return value:

F_DUPFD return value is a new file descriptor
F_GETFD return value to the corresponding flag obtained
F_GETFL return value is the status flag of the file descriptor
F_getown return value If positive is the process ID number, if negative is the process group ID number

function Fcntl () is divided into the following 6 categories:

(1) Copy file descriptor (CMD=FD_DUPFD)

(2) Get/Set file descriptor (CMD=F_GETFD or F_SETFD)

(3) Get/Set File status value (CMD=F_GETFL or F_SETFL)

(4) Get/Set signal sending object (Cmd=f_getlease, F_setown, F_getsig or F_setsig)

(5) Get/Set file record lock (CMD=F_GETLK or f_setlk or f_setlkw)

(6) Obtain/Set file leases (Cmd=f_getlease or f_setlease)

8. File input and Output control IOCTL () function

IOCTL is a shorthand for input output control, which means that the IOCTL () function controls the device by sending commands to the file descriptor.

The function prototype is as follows:

#include <sys/ioctl.h>
int ioctl (int d, int request,...);

Related Article

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.