I have different processes concurrently accessing a named pipe in Linux and I want to make this access mutually exclusive.
I know is possible to achieve that using a mutex placed in a shared memory area, but being this a sort of homework assignment I have some restrictions.
Thus, what I thought about is to use locking primitives on files to achieve mutual exclusion; I made some try but I can’t make it work.
This is what i tried:
flock(lock_file, LOCK_EX)
// critic section
flock(lock_file, LOCK_UN)
Different projects will use different file descriptors but referring to the same file.
Is it possible to achieve something like that? Can you provide some example.
Your example is as good as you’re going to get using
flock (2)(which is after all, merely an “advisory” lock (which is to say not a lock at all, really)). The man page for it on my Mac OS X system has a couple of possibly important provisos:and
both of which suggest ways it could fail.
// would have been a comment, but I wanted to quote the man page at some length