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