When I run my program:
int i = fork();
if (!i){
int id = open("shared.txt", 0600 | O_WRONLY);
if(flock(id, LOCK_EX | LOCK_NB) == -1)
perror("flock_ch");
if(write(id, "child", 5)) printf("child did it\n");
else perror("write_ch");
sleep(3);
close(id);
}
else {
int id = open("shared.txt", 0600 | O_WRONLY);
if(flock(id, LOCK_EX | LOCK_NB) == -1)
perror("flock_PR");
if(write(id, "parent", 6)) printf("parent did it\n");
else perror("write_pr");
sleep(3);
close(id);
}
wait(NULL);
I expect that only one process will write something in the file, but even if the file is locked, two of processes write in the file.
Both processes are writing to the file because you're ignoring the error return value from
flock(). When I run your code, I see:That
flock_ch: Resource temporarily unavailableis becauseflock()is returning with an error and telling you the file is locked. You're printing out an error message, but not otherwise responding to the error message. You probably want to either (a) exit or (b) loop untilflock()succeeds.Using a loop might look like:
Running the above produces:
Alternately, drop the
LOCK_NBflag so thatflock()blocks until the lock is available. That might look like:And running the above produces: