Flock () function example

Source: Internet
Author: User

Note: The process is automatically unlocked when it is rolled back.

# Include <stdio. h> # include <stdlib. h> # include <sys/file. h> // provide the flock () function. From # include, we can see that it is a system call, not a library function # include <unistd. h> // compilation method: // assume the file name is X. CPP, then G ++-g-o X. CPP // a command line parameter argv [1] Must be included. // it must be an existing file path and can be a 0-byte file int main (INT argc, char * argv []) {int FD = open (argv [1], o_rdonly); If (-1 = FD) {perror ("open "); exit (1);} printf ("% d try to get lock \ n", getpid (); // you can lock the lock if you want to allow other locks, lock_sh should be used, and lock_nb should be used for selection. If (-1 = flock (FD, lock_ex) {perror ("flock"); close (FD ); exit (1);} printf ("% d locked now, enter any key to continue... \ n ", getpid (); getchar (); printf (" % d prepare to release lock \ n ", getpid ()); // release the lock if (-1 = flock (FD, lock_un) {perror ("fulock"); close (FD); exit (1 );} printf ("lock was released now \ n"); printf ("process % d exited now \ n", getpid (); close (FD); Return 0 ;}

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.