[cs631apue] [CS 631] Semaphores

Jan Schaumann jschauma at stevens.edu
Thu Nov 15 16:15:23 EST 2012


tparisi <tparisi at stevens.edu> wrote:

> I am trying to use semaphores in the web server to prevent a file from  
> being altered by another process when being read by the server.

A nice idea, but I'm afraid this won't quite accomplish what you want.
Recall that any locking is only advisory and requires cooperating
processes.  That is, only processes that actually check whether or not a
lock exists on a given file would block; any other process would simply
do whatever it wants.

That is, if your web server sets a lock on a file, then only a tool that
checks for this lock would honor it -- all existing system tools,
editors or other executables don't (can't) know that they should check
for a given lock, and thus your locking mechanism doesn't protect you
from file modifications.

In other words: don't make things too complicated and don't worry about
a file changing while you serve it.  If it happens, you will get an
error and simply stop writing data.

> That all works.  My main concern is that in class we were shown that the 
> locks that we create (my understanding is that semaphore lock is  
> attached to a single file)

No, a semaphore is merely an in-kernel data structure that you can
access.  It is not associated with a file -- we just happened to have
used the ftok(3) function to generate a key that can reasonably be
assumed to "unique" for a given file.  The semaphore itself is entirely
oblivious to any files.

> I would like to destroy the lock when the daemon exits.  However, there  
> is only one semaphore ID in the parent process so I'll only be able to  
> destroy on such lock right?  Right now, I'm of the understanding that  
> destroying the lock in the child is a poor choice because another forked  
> child of the parent could be trying to acquire that lock and destroying  
> it would mess the operations up.

Not only that, by using this locking mechanism with exclusive locks,
you'd also prevent more than one client from retrieving a given file
from the server.

> I'm really stumped here so any helpful clues would be just great.

Very easy solution: don't worry about locking at all. :-)

> Also, on a side note, are we allowed to use outside code as long as its  
> cited in someway?

No, any code you hand in and wish to receive credit for needs to have
been written by you.  *If* you include outside code, then it must be
clearly marked as such, including the source, and the license of the
code in question must explicitly permit your use of it.  But as I said,
you will not receive any credit for code blocks that you didn't write.

-Jan


More information about the cs631apue mailing list