Fcntl. h

Source: Internet
Author: User
Tags define function flock

Fcntl. h and unistd. h2008-08-22 22: 15fcntl. h define a lot of macro and open, fcntl function prototype
Unistd. h defines more function prototypes

Close (close the file)
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.
Close () writes data back to the disk and releases the resources occupied by the file. The FD parameter is
The description of the file previously 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: although the system will automatically close opened files at the end of the process, we recommend that you
Close the file and check the returned value. (The system may be buffered and written only when appropriate, especially for the NFS Network File System)

Open (open a file)
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,
However, it can be combined with the following flag 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
O_creat and o_excl are set at the same time, and the file to be opened is a symbolic connection, the file opening 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.
O_noatime starts from Linux 2.6.8 kernel and does not update the last file access time when reading files.
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!

Creat (create a file)
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 an error is returned.
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 mkmod () if necessary ().

DUP (copy file description)
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. The new file description and parameter oldfd refer to the same file, sharing all the locking, read/write locations and various permissions 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. Error code: Invalid document of the ebadf parameter FD
Description, or the file is closed.

Dup2 (copy file description)
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 referred to 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 file to be set.
Description. The cmd parameter indicates the command to operate.
There are several situations:
F_dupfd is used to find the minimum and unused file description that is greater than or equal to the ARG parameter.
And copy the file description of the FD parameter. If the execution is successful, the new copied file is returned.
Description. See dup2 (). F_getfd gets the close-on-exec flag. If this flag
The value of the fd_cloexec mark is 0, indicating that the file will not be closed when the exec () function is called.
.
F_setfd: Set the close-on-exec flag. This flag uses the ARG Parameter
The fd_cloexec bit is determined.
F_getfl gets the flag of the file descriptive word status, which is a parameter of open ().
Flags.
F_setfl sets the file descriptive word status flag. The parameter Arg is the new flag, but only allow
Changes in the o_append, o_nonblock, and o_async bits will not be 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. Error
The code is eacces or eagain.
F_setlkw f_setlk works the same but cannot be used to create a lock.
Wait until the lock action is successful. If a signal is interrupted while waiting for the lock
Return-1 immediately. The error code is eintr. The parameter lock pointer is a flock structure pointer,
The definition is 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 () will perform operations on the files referred to by the parameter FD according to the method specified by the parameter operation.
Lock or unlock. This function can only lock the entire file and cannot lock the file
Parts.
Operation has the following four conditions:
Lock_sh creates a shared lock. Multiple processes can share a lock on the same file at the same time.
Yes.
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. Connect
It is often 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 this 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
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)
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.
The position is to start with the file. If the file is opened in an additional way (such as o_append ),
The read/write location points to the end of the file. When read () or write (),
Added. lseek () is used to control the read/write location of the file. The Fildes parameter is
Description of the opened file. The offset parameter is used to move the read/write Location 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 output.
Now.
Here are some special instructions:
1) to move the read/write location to the beginning of the file: lseek (int
Fildes, 0, seek_set );
2) When you want to move the read/write location 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
Bytes. 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.
() Returns espipe.
Example reference this function description

Read (read data from opened files)
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 Buf pointer within count bytes.
. If the Count parameter is 0, read () does not work and 0 is returned. The returned value is real.
Number of bytes read. If 0 is returned, it indicates that the object has reached the end of the file or cannot be read.
Data, in addition, the file read and write location will move with the read bytes.
Additional instructions: If read () succeeds, the actual number of bytes read will be returned.
Count. If the number of returned bytes is less than the number of required bytes, it is possible
Read to the end of the file, read from the pipeline (PIPE) or terminal, or read () is signal
The read operation is interrupted. -1 is returned when an error occurs. The error code is stored in errno.
But the file read/write location is unpredictable.
Error Code eintr this call is interrupted by the signal.
Eagain: When I/O cannot be blocked (o_nonblock), if no data can be read
Returns this value.
The ebadf parameter FD is a non-valid file description word, or the file is closed.
For an example, see open ().
Sync (write buffer data back to disk)
Related Function fsync
Header file # include <unistd. h>
Define function int sync (void)
Function Description sync () writes the System Buffer data back to the disk to ensure data synchronization.
The return value is 0.
Write (write data into an opened file)
Define the function ssize_t write (int fd, const void * Buf, size_t count );
Function Description: Write () will write the memory referred to by the parameter Buf into the count byte to the text referred to by the parameter FD
. Of course, the file read/write location will also move.
If the return value is successfully written (), the actual number of bytes written will be returned. Returns if an error occurs.
Back to-1. The error code is stored in errno.
Error Code eintr this call is interrupted by the signal.
Eagain: When I/O cannot be blocked (o_nonblock), if no data can be read
Returns this value.
The EADF parameter FD is a non-valid file description word, or the file is closed.
For examples, see open ().

Fork

Traditionally, fork creates a sub-process and creates a copy of the parent process address space for the sub-process. However, since many sub-processes normally execute exec immediately after they are created, replication of the address space of the parent process may not be necessary, resulting in a great waste of efficiency and memory. Therefore, a technology called "Copy at write time" is created.

This is a copy-on-write operation.

During write replication, the child process and the parent process can share the same page at the start. However, these pages are marked as "Copy at write time", that is, if any process needs to write to the page, a copy of the shared page will be created. For example, if a sub-process attempts to modify a page containing some stacks and the operating system can recognize the page as a copy-on-write page, the operating system creates a copy of the page, and map it to the address space of the child process. In this case, the child process modifies the copied page rather than the parent process page. With the write-time replication technology, only the pages modified by the process are copied, and all non-modified pages can be shared by the parent process and child process. Note: not all pages are marked as write copy. Only the pages that may be modified need to be marked as write copy. For pages that cannot be modified, such as the code page, shared by Parent and Child processes.

Vfork (Virtual Memory fork)

Vfork is not the same as the fork copied during write. For vfork, the parent process is suspended to ensure that the child process runs first. The child process uses the address space of the parent process. Because vfork does not use Write-time replication, if the child process modifies any page of the address space, these modifications are visible when the parent process restarts. Therefore, vfork must be used with caution to ensure that the child process does not modify the address space of the parent process. Vfork is mainly used to call exec immediately after the process is created, so that there is no copy page or the address space of the parent process is not modified, so it is a very effective process creation method.

Char * getcwd (char * Buf, size_t size );
# Include <stdio. h>
# Include <unistd. h>
# Include <limits. h>
/*
* If limits. h no define path_max, I define.
*/
# Ifndef path_max
# Define path_max 255
# Endif

Int main (){
Char workdir [path_max];
If (! Getcwd (workdir, path_max ))
Perror ("couldn't get current work directory! /N ");
Else
Printf ("workdir = % s/n", workdir );
Return 0;
}

Long pathconf (char * path, int name );
Int chdir (const char * path );
# Include <stdio. h>
# Include <unistd. h>
# Include <limits. h>
# Include <stdlib. h>

Int main (){
Char * workdir;
Long path_max;

If (path_max = pathconf ("/", _ pc_path_max) =-1 ){
Perror ("couldn't get _ pc_path_max! /N ");
Return-1;
}
Printf ("path_max is % d/N", path_max );

If (workdir = (char *) malloc (path_max) = NULL ){
Perror ("couldn't allocate memory for the workdir! /N ");
Return-1;
}
If (getcwd (workdir, path_max) = NULL ){
Perror ("couldn't get current work directory! /N ");
Return-1;
}

Printf ("Current DIR is % s/n", workdir );

If (chdir ("..") =-1 ){
Perror ("Change directory error! /N ");
Return-1;
}
If (getcwd (workdir, path_max) = NULL ){
Perror ("couldn't get current work directory! /N ");
Return-1;
}

Printf ("Current DIR is % s/n", workdir );

Free (workdir );
Return 0;
}

Int rmdir (const char * pathname );

Int chown (const char * path, uid_t owner, gid_t group );
Int fchown (int fd, uid_t owner, gid_t group );
Int lchown (const char * path, uid_t owner, gid_t group );
Int unlink (const char * pathname );
Int Link (const char * oldpath, const char * newpath );
Int symlink (const char * oldpath, const char * newpath); // symbolic links soft connection

Char * ttyname (int fd );
# Include <stdio. h>
# Include <unistd. h>
# Include <limits. h>
# Include <stdlib. h>
# Include <sys/types. h>
# Include <sys/STAT. h>

Int main (INT argc, char * argv []) {
Char * tty_out;

If (tty_out = ttyname (stdout_fileno) = NULL ){
Perror ("cannot get tty name/N ");
Return-1;
}
Printf ("stdout_fileno tty name is: % s/n", tty_out );
Return 0;
}

Void usleep (unsigned long USEC); millisecond

Pid_t getpid (void );
Pid_t getppid (void );
Uid_t getuid (void );
Uid_t geteuid (void );
Gid_t getgid (void );
Gid_t getegid (void );

Int execl (const char * path, const char * Arg ,...); int execlp (const char * file, const char * Arg ,...); int execle (const char * path, const char * Arg ,..., char * const envp []); int execv (const char * path, char * const argv []); int execvp (const char * file, char * const argv []); int execve (const char * path, char * const argv [], char * const envp []); pid_t setsid (void); int lockf (int fd, int cmd, off_t Len); unsigned int alarm (unsigned int seconds); int pipe (INT pipefd [2]);
 

 

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.