Is it possible to use fcntl() inside a function other than main() ? Does the file get unlocked after calling it ? I say this because in this case fcntl() and most everything else inside lockfile() are out-of-scope when the function returns.
int lockfile(void){
int fd;
const char *path = "path-to-lockfile";
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0
fl.l_pid = getpid();
fd = open(path, O_RDWR|O_CREAT);
fcntl(fd, F_SETLKW, &fl);
return fd;
}
The
fcntlcall places a lock on the file. It remains until the file is closed or the lock is released. The structures are only needed to tellfcntlwhat to do.