Roles of sys/types. h and fcntl. h

Source: Internet
Author: User
Tags flock

Sys/types. h

Is the header file of the basic system data type of Unix/Linux systems, including size_t, time_t, pid_t and other types.

The application source file contains <sys/types. h> to access the definition of _ lp64 and _ ilp32. This header file also contains multiple basic derived types that should be used when appropriate. In particular, the following types are more important:

Clock_t indicates the system time (in the unit of clock cycle ).

Dev_t indicates the device number.

Off_t is used for file size and offset.

Ptrdiff_t is a signed integer used to perform the subtraction operation on the two pointers.

Size_t indicates the size of objects in the memory (in bytes ).

Ssize_t is used by the function that returns the byte count or error message.

Time_t is measured in seconds.

All these types are maintained as 32-bit values in the ilp32 compiling environment and will be extended to 64-bit values in the lp64 compiling environment.

Blkcnt_t used for file block counts.

Blksize_t used for block sizes.

Clock_t used for system times in clock ticks or clocks_per_sec; see <time. h>.

Clockid_t used for clock ID type in the clock and timer functions.

Dev_t used for device IDs.

Fsblkcnt_t
Used for file system block counts.

Fsfilcnt_t
Used for File System File counts.

Gid_t used for group IDs.

Id_t used as a general identifier; can be used to contain at least a pid_t, uid_t, or gid_t.

Ino_t used for file serial numbers.

Key_t used for xsi interprocess communication.

Mode_t used for some file attributes.

Nlink_t used for link counts.

Off_t used for file sizes.

Pid_t used for process IDs and process group IDs.

Size_t used for sizes of objects.

Ssize_t used for a count of bytes or an error indication.

Suseconds_t
Used for time in microseconds.

Time_t used for time in seconds.

Timer_t used for timer ID returned by timer_create ().

Trace_attr_t used to identify a trace stream attributes object.

Trace_event_id_t used to identify a trace event type.

Trace_event_set_t used to identify a trace event type set.

Trace_id_t used to identify a trace stream.

Uid_t used for user IDs.

Useconds_t used for time in microseconds.

All of the types shall be defined as arithmetic types of an appropriate length, with the following exceptions:

Key_t
Additionally:
* Mode_t shall be an integer type.
* Nlink_t, uid_t, gid_t, and id_t shall be integer types.
* Blkcnt_t and off_t shall be signed integer types.
* Fsblkcnt_t, fsfilcnt_t, and ino_t shall be defined as unsigned integer types.
* Size_t shall be an unsigned integer type.
* Blksize_t, pid_t, and ssize_t shall be signed integer types.
* Time_t and clock_t shall be integer or real-floating types.

 

Fcntl. h header file

Close (close the file)
Related functions: open, fcntl, shutdown, unlink, and fclose

Header file # include <unistd. h>

Defines the int close (int fd) function );

Function Description: After a file is used, close () can be used to close the file if it is no longer needed. Second close () will write data back to the disk and release the resources occupied by the file. The FD parameter is the description of the file returned by open () or creat.

If the file is closed successfully, 0 is returned. If an error occurs,-1 is returned.

The error code is an invalid file description of the parameter FD (ebadf) or the file is closed.

Note that although the system will automatically close opened files at the end of the process, we recommend that you close the files and check the returned values.

For more information, see open ()

Creat (create a file)
Related functions: read, write, fcntl, close, Link, stat, umask, unlink, and fopen

Header file # include <sys/types. h>
# Include <sys/STAT. h>
# Include <Fcntl. h>

Define the function int creat (const char * pathname, mode_tmode );

Function Description: The pathname parameter points to the file path string to be created. Creat () is equivalent to calling open () using the following call Methods ()
Open (const char * pathname, (o_creat | o_wronly | o_trunc ));

For error code about the parameter mode, see open () function.

If the return value is creat (), a new file description is returned. If an error occurs,-1 is returned, and the error code is set to errno.
The file specified by the eexist parameter pathname already exists.
The file specified by the eaccess parameter pathname does not meet the required permissions.
The file to which erofs wants to open the write permission exists in the read-only file system.
The pathname pointer of the efault parameter exceeds the accessible memory space.
The Mode Val parameter mode is incorrect.
The pathname parameter of enametoolong is too long.
The pathname parameter of enotdir is a directory.
Insufficient enomem core memory
The pathname parameter of eloop has too many symbolic connections.
Emfile has reached the maximum number of files that can be opened simultaneously by the process.
Enfile has reached the maximum number of files that can be opened simultaneously by the system.

Additional instructions creat () cannot create special device files. Use mknod () if necessary ().

For examples, see open ().

DUP (copy file description)
Related functions: open, close, fcntl, dup2

Header file # include <unistd. h>

Defines the int DUP (INT oldfd) function );

The function description DUP () is used to copy the file description referred to by the oldfd parameter and return it. This new file descriptive word and parameter oldfd refer to the same file, sharing all locking, read/write locations, and various ACLs or flag. For example, when lseek () is used to describe a file, the read/write location of the descriptive word of another file also changes. However, file descriptions do not share the close-on-exec flag.

When the replication is successful, the minimum and unused file description words are returned. If an error occurs,-1 is returned, and errno stores the error code. The error code ebadf parameter FD is a non-valid file description word, or the file is disabled.

Dup2 (copy file description)
Related functions: open, close, fcntl, DUP

Header file # include <unistd. h>

Defines the int dup2 (INT odlfd, int newfd) function );

Function Description: dup2 () is used to copy the file description word referred to by the oldfd parameter and copy it to the newfd parameter. If newfd is an opened file description, the file specified by newfd is closed first. The file description word copied by dup2 () shares various file states with the original file description word. For details, see DUP ().

When the replication is successful, the minimum and unused file description words are returned. If an error occurs,-1 is returned, and errno stores the error code.

Additional instructions dup2 () is equivalent to calling fcntl (oldfd, f_dupfd, newfd); see fcntl ().

Error code: invalid file description in the parameter fd of the ebadf, or the file is disabled

Fcntl (File description operations)
Related functions: open and flock

Header file # include <unistd. h>
# Include <Fcntl. h>

Defines the int fcntl (int fd, int cmd) function );
Int fcntl (int fd, int cmd, long Arg );
Int fcntl (int fd, int cmd, struct flock * Lock );

Function Description: fcntl () is used to operate on some features of file descriptors. The FD parameter indicates the description of the file to be set, and the CMD parameter indicates the command to be operated.
There are several situations:
F_dupfd is used to find the smallest and unused file description words greater than or equal to the ARG parameter, and copy the file description words of the parameter FD. If the execution is successful, the new copied file description is returned. See dup2 (). F_getfd gets the close-on-exec flag. If the fd_cloexec bit of the flag is 0, the file will not be closed when the exec () function is called.

F_setfd: Set the close-on-exec flag. The flag is determined by the fd_cloexec bit of the ARG parameter.
F_getfl gets the flag of the file descriptive word status, which is the flags parameter of open.
F_setfl sets the State Flag of the description word in the file. The ARG parameter is the new flag, but only changes to the o_append, o_nonblock, and o_async bits are allowed. Changes to other bits are not affected.
F_getlk: get the file lock status.
F_setlk sets the file lock status. The l_type value of the flcok structure must be f_rdlck, f_wrlck, or f_unlck. If a lock cannot be created,-1 is returned. The error code is eacces or eagain.

F_setlkw f_setlk works the same, but the lock cannot be established. This call will wait until the lock action is successful. If a signal is interrupted while waiting for the lock,-1 is returned immediately and the error code is eintr. The parameter lock pointer is a flock structure pointer and is defined as follows:

Struct flcok
{
Short int l_type;/* locked status */
Short int l_whence;/* determines the Rochelle start position */
Off_t l_start;/* start position of the locked area */
Off_t l_len;/* size of the locked area */
Pid_t l_pid;/* Lock action process */
};
Rochelle type has three statuses:
F_rdlck creates a lock for reading
F_wrlck creates a lock for writing
F_unlck Delete the previously created lock
Rochelle whence also has three methods:
Seek_set starts with a file and is the starting position of the lock.
Seek_cur uses the current file read/write location as the starting position of the lock
The start position of seek_end lock is the end of the file.

If the return value is successful, 0 is returned. If an error exists,-1 is returned. The error cause is stored in errno.

Flock (lock file or unlock)
Related functions: open, fcntl

Header file # include <sys/file. h>

Defines the int flock (int fd, int operation) function );

Function Description: Flock () performs various locking or unlocking actions on the file referred to by the parameter FD according to the method specified by the parameter operation. This function can only lock the entire file and cannot lock a certain area of the file.

Operation has the following four conditions:
Lock_sh creates a shared lock. Multiple processes can share and lock the same file at the same time.
Lock_ex creates a mutex lock. One file has only one mutex lock.
Lock_un unlocks the file.
Lock_nb cannot be used to establish a lock. This operation is not blocked and the process is returned immediately. Usually it is combined with lock_sh or lock_ex or (|.
Shared locks and mutex locks cannot be created for a single file. When DUP () or fork () is used, the file description does not inherit the lock.

If the return value is 0, a success is returned. If an error exists,-1 is returned. The error code is stored in errno.

Fsync (write buffer data back to disk)
Related Function sync

Header file # include <unistd. h>

Defines the int fsync (int fd) function );

Function Description fsync () is responsible for writing the file data referred to by the FD parameter back to the disk by the system buffer to ensure data synchronization.

If the return value is successful, 0 is returned,-1 is returned for failure, and errno is the error code.

Lseek (read/write location of mobile files)
Related functions dup, open, fseek

Header file # include <sys/types. h>
# Include <unistd. h>

Define the off_t lseek function (INT Fildes, off_t offset, int whence );

Function Description: each opened file has a read/write location. When a file is opened, its read/write Location usually points to the beginning of the file. If the file is opened in an additional way (such as o_append ), the read/write position points to the end of the file. When read () or write (), the read/write location increases accordingly, and lseek () is used to control the read/write location of the file. The Fildes parameter is the description of an opened file, and the offset parameter is the number of read/write locations to be moved Based on the whence parameter.

The whence parameter is one of the following:
The seek_set parameter offset is the new read/write location.
Seek_cur increases the offset displacement at the current read/write position.
Seek_end points the read/write position to the end of the file and then increases the offset displacement.
When the whence value is seek_cur or seek_end, The offet parameter allows negative values.
Here are some special instructions:
1) to move the read/write position to the beginning of the file: lseek (INT Fildes, 0, seek_set );
2) When you want to move the read/write position to the end of the file: lseek (INT Fildes, 0, seek_end );
3) to obtain the current file location: lseek (INT Fildes, 0, seek_cur );

Return value when the call is successful, the current read/write location is returned, that is, the number of bytes from the beginning of the file. If an error occurs,-1 is returned, and errno stores the error code.

Additionally, the Linux system does not allow lseek () to act on the tty device. This action causes lseek () to return espipe.

Example reference this function description

Mkstemp (create a unique temporary file)
Related functions: mktemp

Header file # include <stdlib. h>

Defines the int mkstemp (char * template) function );

Function Description mkstemp () is used to create a unique temporary file. The last six characters in the file name string referred to by the template parameter must be xxxxxx. Mkstemp () can open the file in read/write mode and with 0600 permissions. If the file does not exist, the file will be created. After the file is opened, its description is returned. After the file is successfully opened, the system returns the description word of the file that can be read and written. If the file fails to be opened, null is returned and the error code is stored in errno.

The error code einval parameter specifies that the last six characters of the template string are not xxxxxx. Eexist cannot create temporary files.

Additional instructions: the file name string referred to by the template parameter must be declared as an array, for example:
Char template [] = "template-xxxxxx ";
Do not use the following expressions
Char * template = "template-xxxxxx ";

Example # include <stdlib. h>
Main ()
{
Int FD;
Char template [] = "template-xxxxxx ";
FD = mkstemp (Template );
Printf ("template = % s \ n", template );
Close (FD );
}

Execute template = template-lgzcbo

Open (open a file)
Related functions: read, write, fcntl, close, Link, stat, umask, unlink, and fopen

Header file # include <sys/types. h>
# Include <sys/STAT. h>
# Include <Fcntl. h>

Define the int open (const char * pathname, int flags) function );
Int open (const char * pathname, int flags, mode_t mode );

Function Description: The pathname parameter points to the file path string to be opened. The following are flags that can be used by the flags parameter:
O_rdonly open a file in read-only mode
O_wronly open the file in write-only mode
O_rdwr can open files in read/write mode. The above three flags are mutually exclusive, that is, they cannot be used at the same time, but can be combined with the following flags using the OR (|) operator.
O_creat: if the file to be opened does not exist, the file is automatically created.
O_excl if o_creat is also set, this command checks whether the file exists. If the file does not exist, the file will be created; otherwise, the file will be opened incorrectly. In addition, if both o_creat and o_excl are set and the file to be opened is a symbolic connection, opening the file will fail.

If the file to be opened is a terminal device, o_noctty does not regard the terminal as a process control terminal.
If the o_trunc file exists and is opened in writable mode, this flag will clear the file length to 0, and the information originally stored in the file will also disappear.
O_append when reading and writing a file, it will start to move from the end of the file, that is, the written data will be appended to the end of the file.
O_nonblock open the file in an unblocking way, that is, whether there is data read or waiting, it will immediately return to the process.
O_ndelay is the same as o_nonblock.
O_sync opens the file in synchronous mode.
O_nofollow if the file indicated by pathname is a symbolic connection, opening the file will fail.
O_directory if the file indicated by the pathname parameter is not a directory, opening the file will fail.
This is a flag unique after linux2.2 to avoid some system security problems. The mode parameter has the following combinations. This parameter takes effect only when a new file is created. In addition, the permissions for creating a file are affected by the umask value, therefore, the file permission should be (Mode-umaks ).

S_irwxu00700 permission indicates that the object owner has the readable, writable, and executable permissions.
S_irusr, s_iread, and 00400 permissions indicate that the file owner has the readable permission.
S_iwusr or s_iwrite, 00200 permission indicates that the file owner has the write permission.
S_ixusr or s_iexec, 00100 permission indicates that the file owner has executable permission.
S_irwxg 00070 permission indicates that the file user group has the readable, writable, and executable permissions.
S_irgrp 00040 permission indicates that the file user group has the readable permission.
S_iwgrp 00020 permission indicates that the file user group has the write permission.
S_ixgrp 00010 permission indicates that the file user group has executable permissions.
S_irwxo 00007 indicates that other users have the readable, writable, and executable permissions.
S_iroth 00004 permission, which indicates that other users have the readable permission
S_iwoth 00002 permission indicates that other users have the write permission.
S_ixoth 00001 permission indicates that other users have executable permissions.

Return Value: if all the permissions to be verified have passed the check, 0 is returned, indicating success. If one permission is disabled,-1 is returned.

The file indicated by the error code eexist parameter pathname already exists, but the o_creat and o_excl flag are used.
The file indicated by the eaccess parameter pathname does not meet the required permissions.
The file to be tested by erofs is stored in the read-only file system.
The pathname pointer of the efault parameter exceeds the accessible memory space.
The Mode Val parameter mode is incorrect.
The pathname parameter of enametoolong is too long.
The pathname parameter of enotdir is not a directory.
The enomem core memory is insufficient.
The pathname parameter of eloop has too many symbolic connections.
Eio I/O access error.

Note that you must be especially careful when using access () for user authentication. For example, making an open () empty file after access () may cause system security problems.

Example # include <unistd. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <Fcntl. h>

Main ()
{
Int FD, size;
Char s [] = "Linux programmer! \ N ", buffer [80];
FD = open ("/tmp/Temp", o_wronly | o_creat );
Write (FD, S, sizeof (s ));
Close (FD );
FD = open ("/tmp/Temp", o_rdonly );
Size = read (FD, buffer, sizeof (buffer ));
Close (FD );
Printf ("% s", buffer );
}

Run Linux programmer!

Read (read data from opened files)
Related functions: readdir, write, fcntl, close, lseek, readlink, and fread

Header file # include <unistd. h>

Define the function ssize_t read (int fd, void * Buf, size_t count );

Function Description: Read () transfers the file referred to by the FD parameter to the memory indicated by the Buf pointer in count bytes. If the Count parameter is 0, read () does not work and 0 is returned. The returned value is the number of bytes actually read. If 0 is returned, it indicates that the data has reached the end of the file or cannot be read. In addition, the read/write location of the file will move with the read bytes.

Additional instructions: If read () is successful, the actual number of bytes read will be returned. It is best to compare the returned value with the parameter count. If the returned number of bytes is less than the required number of bytes, it is possible to read the end of the file, read from the pipe or terminal, or read () is interrupted by the signal. -1 is returned when an error occurs. The error code is saved.

 

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.