The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Advanced & Expert Users
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 08-28-2007
Neo's Avatar
Neo Neo is online now Forum Staff  
Administrator
  
 

Join Date: Sep 2000
Location: Asia Pacific
Posts: 6,683
Semaphores are not inherently linked to memory, processes, code or files.

Semaphores are flags that processes, including processes that access files or shared memory, use to know a guaranteed status, which is often referred to as "atomic".

Let's say you are writing a shared memory application. You don't want to read or write to shared memory when another process is writing to it (if that process has write permissions). Also, you don't want to read a file that is being changed, etc. So, you create a semaphore and you designate two states:

- semaphore set, means that a process with write permission has a file descriptor open.

- semaphore clear, means that there is no process with write permissions accessing the shared memory.

Now, each process that accesses the shared memory must check the status of the semaphore when they (it) open the file (in this case shared memory) for access.

There are many applications for semaphores for interprocess communications, not limited to shared memory; but shared memory certainly required atomic flags for interprocess communications.

Think of this like a person on a single track of train track holding a flag. One train is flying down the track at 200 kph in one direction and other train is heading toward the same track segment from the opposite direction. There is a switch at one section of track where one train can wait while the other passes. A switchman, in the old days, would hold up a flag (later done with lights) to give status to both trains.

You can see that trusting the flags by the switchman is critically important, folks could dies if the flag is incorrect or the conductor of the train does not watch it.

The same is true in interprocess communications, and semaphores are guaranteed by the UNIX / Linux kernel to be atomic, dead right on.

File locks are not guaranteed by the kernel to be atomic, as I recall, so use them with caution.