How do I lock files using fopen()?

前端 未结 7 1914
时光取名叫无心
时光取名叫无心 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:29

    Note that in below code fopen will fail (and return NULL) if the lock file /var/lock/my.lock doesn't exist.

    FILE* f = fopen("/var/lock/my.lock", "r");
    int result = flock(fileno(f)), LOCK_SH);
    

    Use fopen with w+ if you need the lockfile to be created if it doesn't exist.

    FILE* f = fopen("/var/lock/my.lock", "w+");
    int result = flock(fileno(f)), LOCK_SH);
    
    0 讨论(0)
提交回复
热议问题