LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Issue with semaphore implementation (https://www.linuxquestions.org/questions/programming-9/issue-with-semaphore-implementation-534218/)

ketanu 03-03-2007 11:38 AM

Issue with semaphore implementation
 
I am trying to create a semaphore between two of my processes. Process tht created the semaphore got killed. Now i am unable to create the semaphore with the same key when i restart this process. i cannot restart my system . Is there any way tht the kernel destroys this "orphaned" semaphore, which is used by none of the processes.

wjevans_7d1@yahoo.co 03-03-2007 12:09 PM

I can think of four ways around this.
  1. If you have root access, you can delete the semaphore that way.
  2. If the semaphore still exists from a previous run, just use it. This alternative is scary, because you don't know the current state of the semaphore.
  3. Don't use a constant key. Use IPC_PRIVATE instead, and find a way to communicate the value of the resultant key from one process to the other. The disadvantage to this is that if you kill your processes too many times, you're going to run out of systemwide semaphores. I'm fairly sure there's a set maximum. Dorky, but there you are.
  4. The best best best way is not to use semaphores at all. Use file locking. Create a file (it can contain zero bytes) whose only purpose is synchronization. This way, the situation degrades gracefully when the processes die, and the implementation doesn't have what-ifs or gotchas.

ketanu 03-03-2007 12:20 PM

thnx wjevans 4 such a prompt reply.

Well i m a windows programmer basically, and i've just started with Linux. In windows these orphaned semaphores are automatically deleted when none of the process holds a handle for it. Is there any similar house keeping done by linux kernel. Can i set any kernel parameters to do the same.

wjevans_7d1@yahoo.co 03-04-2007 08:45 AM

No, there are no Unix/Linux housekeeping arrangements for orphaned semaphores. This is a "feature", though in your case it doesn't work to your benefit. No kernel parameters, no nothing.

Record locking in Unix/Linux fills the bill. For any range of bytes in a file (even bytes which do not actually exist in the file), you can:
  • set a reader's lock, and return if that cannot be done immediately;
  • set a reader's lock, waiting until it can be done if necessary and not returning until it has been done;
  • do the same things for a writer's lock;
  • release a lock; and
  • test the state of a lock without changing it.

The best decription I've seen of this is in Advanced Programming in the UNIX Environment, by W. Richard Stevens (of happy memory). (That means he's dead now.) But you can get a pretty good description of record locking by doing:

Code:

man fcntl
Hope this helps.


All times are GMT -5. The time now is 11:17 PM.