How do I lock files using fopen()?

前端 未结 7 1946
时光取名叫无心
时光取名叫无心 2020-12-01 06:41

I wonder if there is any way to lock and unlock a file in Linux when I open a file using fopen (not open)?

Based on Stack Overflow question

7条回答
  •  日久生厌
    2020-12-01 07:20

    Files can be locked by using flock(). Its syntax is

     #include 
     #define   LOCK_SH   1    /* shared lock */
     #define   LOCK_EX   2    /* exclusive lock */
     #define   LOCK_NB   4    /* don't block when locking */
     #define   LOCK_UN   8    /* unlock */
    
    int flock(int fd, int operation);
    

    First file is opened using fopen() or open(). Then this opened file is locked using flock() as given below

    int fd = open("test.txt","r");
    int lock = flock(fd, LOCK_SH);  // Lock the file . . .
    // . . . .
    // Locked file in use 
    // . . . .
    int release = flock(fd, LOCK_UN);  // Unlock the file . . .
    

提交回复
热议问题