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 ;}