Gnu_linux Programming Guide Reading Notes 2 -- Input and Output

Source: Internet
Author: User
Tags flock
1. Use file descriptors
1. open and close the file descriptor.
Open creat must contain the header file <sys/types. h> <sys/STAT. h> and <fcntl. h>
Int open (const char * pathname, int flags)
Int creat (const char * pathname, int flags, mode_t Mode)
Pathname: path name
Flag: how to access the file, o_rdonly o_wronly o_rdwr
Mode: contains the file creation mode.

O_creat: Creates a file if the file does not exist.
O_excl is used only with o_creat. If the file already exists, the forced open fails.
If the file opened by o_noctty is a terminal, it will not be the control terminal for opening the process.
O_trunc if the file exists, the file length is cut to 0
O_append: sets the file pointer to the end of the file.
O_nonblock: If the read operation does not have blocking, the read operation returns 0 bytes.
O_nodelay and o_nonablock
O_sync is returned only after data is physically written to a disk or another device.

FD = open (path, o_creat | o_trunc | o_wronly, 0644 );

2. Read and Write file descriptors
# Inlcue <unistd. h>
Ssize_t read (int fd, const void * Buf, size_t count );
Ssize_t write (int fd, const void * Buf, size_t count );

3. Use ftruncate to shorten files
# Include <unistd. h>
Int ftruncate (int fd, off_t length)

4. Use lseek to locate the file pointer
The lseek function sets the file pointer in the file opened with the descriptor FD to the offset relative to the whence value. The file pointer is the position where the file performs read/write operations.
# Include <sys/types. h>
# Include <unistd. h>
Off_t lseek (int fd, off_t offset, int whence)

Whence:
Seek_set sets the file pointer to the offset byte in the file.
Seek_cur sets the pointer position relative to the current position to the forward offset byte, the offset can be negative
Seek_end: sets the pointer position to offset byte from the end of the file.

Use fsync to synchronize data to the hard disk
# Include <unistd. h>
Int fsync (int fd );

5. Use fstat to obtain file information
The system calls fstat to return information about the file referenced by the file descriptor FD, and stores the result in the structure struct stat pointed to by the Buf.
# Include <sys/STAT. h>
Int fstat (int fd, struct stat * BUF );
Struct stat
{
Dev_t st_dev;
Ino_t st_ino;
Mode_t st_mode;
Nlink_t st_nlink;
Uid_t st_uid;
Gid_t st_gid;
Dev_t st_rdev;
Off_t st_size
Unsigned long st_blksize
Unsigned long st_blocks
Time_t st_atime;
Time_t st_mtime;
Time_t st_ctime;
}

S_islnk (mode) Symbolic Link
S_isreg (mode) Common File
S_isdir (mode) Directory
S_ischr (mode) character device
S_siblk (mode) block Device
S_isfifo (mode) FIFO
S_issock (mode) socket

Use s_ifmt to mask the file-type bits in file mode. Only the file mode with the permission bit and modifier bit is displayed.

6. Create a temporary file in mkstemp Linux
Mkstemp has only one parameter, which ends with "XXXXXXXXX ".

7. Use fchown to change File Ownership
System Call fchown isProgramThe equivalent body of the CHOWN command, which allows you to change the owner and all groups associated with opening the file.
# Include <sys/types. h>
# Include <unistd. h>
Int fchown (int fd, uid_t owner, gid_t group );

8. Use fchmod to change file read/write permissions
The fchmod call changes the permission bits of the file referenced by FD to the octal mode specified by mode.
Int fchmod (int fd, mode_t Mode)

9 flock
Int flock (int fd, int Operation)
Operation:
Lock_sh shared lock
Lock_ex exclusive lock
Lock_nb can perform "or" operations with other values to prevent locking.
At any specific time, only one process can apply an exclusive lock on a file, but multiple processes can apply a shared lock. The lock works only when a program tries to apply its own lock, and the program that does not try to lock the file can still access the file. Therefore, the lock can only work between programs that work collaboratively.
To access a locked file
1) Check for Lock
2) If the file does not have a lock, create your own lock.
3) open the file
4) process files as necessary
5) close the file
6) unlock a file

There are two types of File locks: The commit lock and the mandatory lock.

Advisory lock is also called a cooperative lock. It relies on such conventions. Every process that uses a lock file must check whether a lock exists and respect the existing lock.

The mamdatory lock is executed by the kernel. When a file is locked for write operations, before the process that locks the file releases the lock, the kernel will block any read or write access to the file.

There are two locking methods:
Lock files and records
Flock is used to apply a commit lock to a file
Fcntl and its Package function lockf can either apply a commit lock to the file or apply a mandatory lock. The system calls fcntl to comply with POSIX standards.

Record lock: for a part of the file rather than the entire file lock, such a process with more detailed control over the lock behavior can better write to share file resources

Read locks are also called shared locks, because multiple processes can create read locks on the same part of the file.
The write lock is often used as an exclusive lock because only one process can create a write lock on a part of the file at any time.

# 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 );

Fcntl changes the attributes associated with the file descriptor FD. The cmd parameter controls what fcntl performs.
CMD:
F_dupfd copy file descriptor FD
F_getfd: Get the close-on-exec flag of FD. If the flag is not set and is still 0, the file remains open after being called by the exec series.
F_setfd set the close-on-exec flag to transfer the value in ARG
F_getfl
F_setfl flag for changing open settings
F_getlk get the discrete file lock
F_setlk: Get the discrete filelock without waiting.
F_setlkw is used to obtain the discrete file lock. wait when necessary.
F_getown check the process ID or group number that will receive sigio and sigurg Signals
F_setown: set the process ID or process group number

When setting the lock, you need to pass the parameter with the value f_setlk or f_setlkw and set the value of lock. l_type to f_rdlck (used to read the lock) f_wrlck (used to write the lock ). To clear the lock, Set lock. l_type to f_unlck. Whether set or cleared, if the operation is successful, fcntl returns 0. -1 is returned if the lock cannot be set.

To check the lock status, you can use f_getlk. If another process has been set, related information will be filled in the mechanism of Flock.

10 using DUP and dup2
The system calls DUP and dup2 to copy file descriptors. DUP returns a new file descriptor (the smallest number of file descriptors not used ). Dup2 allows the user to specify the value of the returned file descriptor. If necessary, it first approaches the value of newfd, which is usually used to re-open or redirect a file descriptor.
# Include <unistd. h>
Int DUP (INT oldfd );
Int dup2 (INT oldfd, int newfd );
The offset, flag, and lock of the New and Old descriptors shared files, but do not share the close-on-exec flag.

Dup2 (FD, stdout_fileno)
Close (FD );
Close (stdout_fileno );

11 using select to read and write multiple files at the same time
Int select (int n, fd_set * readfds, fd_set * writefds, fd_set limit TFDs, struct timeval * timeout)
A collection of file descriptors in readfds for reading objects.
In the writefds set, check whether they can write data.
Ry in exceptfds for exception

When an I/O operation returns immediately without waiting, it is called a non-blocking I/O call.

The first parameter n contains the file descriptor of the highest number in any monitored set plus 1. If an error occurs, select returns-1
In the case of an error, select also makes all file descriptor ry and timeout null, so you must reset them to valid values before using them again.

 

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.