Linux File lock: synchronization between processes tutorial, linux File lock

Source: Internet
Author: User
Tags flock

Linux File lock: synchronization between processes tutorial, linux File lock

I. Scenarios

In addition to semaphores and shared memory (atomic operation) synchronization, multi-process synchronization can also be implemented using File locks.

II. Implementation

There are two methods in linux: flock () function and fcntl () function. The results are roughly the same.

Flock function:

Fd: file descriptor

Operation: LOCK_SH (adding a shared lock is equivalent to a read lock), LOCK_EX (adding an exclusive lock is equivalent to a write lock), LOCK_UN (removing the lock added to the file and unlocking ),

LOCK_NB, directly return results)

Fcntl function:

The file lock is:

Int fcntl (int fd, int cmd, struct flock *);

Struct flock definition:

Fd: file descriptor

Cmd: F_GETLK (get file lock information, query), F_SETLK (set file lock information, lock, unlock, no blocking by default), F_SETLKW (set file lock information, lock, unlock, default blocking)

Struct flock l_type: F_RDLCK (read lock), F_WRLCK (write lock), F_UNLCK (unlock)

Struct flock l_whence: Specifies the position of the file to be locked. When used, you can set the same position to achieve the locking effect. SEEK_SET (starting with the file), SEEK_CUR (current position of the file ), SEEK_END (end of the file)

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.