Question

Clean-up IPC resources after a process crash

Asked by: sephi

Unix does not clean up IPC resources (semaphores and shared memory) after a process crash.
Is there a way to bypass the problem?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2000-01-16 at 23:15:22ID10260476
Tags

ipc

,

unix

Topic

Unix Systems Programming

Participating Experts
5
Points
250
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ORA-27500-27650 IPC Error
    Hi, I got this oracle error. ORA-27500 : inter-instance IPC error. Cause : Most likely OS system call error Action : Check extra information and contact Oracle Worldwide Support If I was rebooted System, it's work. Oracle version 8.0.5.2 O/S Solaris 2.6 King regards,
  2. IPC_CREAT and Semaphores...
    Hello. I am working on a project with semaphores, and they are new to me as a programmer. Basically, what I need to do is clear up what the man pages are saying about them. I am using semget() to create a semaphore, and I am using the following statement to create it: #de...
  3. vb6 code crashes once compiled (IPC msg reciever)
    I am using the following code to recieve IPC messages from a Delphi dll. This vb code (the reciever) runs fun in the developer but crashes once run as a compiled exe. Here is the code for the delphi dll and vb6 exe. I can't even comment out everything in the vb6 callback f...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sephiPosted on 2000-01-16 at 23:19:44ID: 2358465

I'll, also appreciate a reference to online or paper literature.

 

by: bedotPosted on 2000-01-17 at 04:44:12ID: 2359048

here the result of man ipcrm, which is rhe command to remove ipc giving for each, id or key, whis are furnished by ipcs (ipc status)


 ipcrm(1)                                                           ipcrm(1)

 NAME
      ipcrm - remove a message queue, semaphore set, or shared memory
      identifier

 SYNOPSIS
      ipcrm [option]...

 DESCRIPTION
      The ipcrm command removes one or more specified message queue,
      semaphore set, or shared memory identifiers.

    Options
      The identifiers are specified by the following options:

           -m shmid       Remove the shared memory identifier shmid from the
                          system.  The shared memory segment and data
                          structure associated with it are destroyed after
                          the last detach.

           -q msqid       Remove the message queue identifier msqid from the
                          system and destroy the message queue and data
                          structure associated with it.

           -s semid       Remove the semaphore identifier semid from the
                          system and destroy the set of semaphores and data
                          structure associated with it.

           -M shmkey      Remove the shared memory identifier, created with
                          key shmkey, from the system.  The shared memory
                          segment and data structure associated with it are
                          destroyed after the last detach.

           -Q msgkey      Remove the message queue identifier, created with
                          key msgkey, from the system and destroy the
                          message queue and data structure associated with
                          it.

           -S semkey      Remove the semaphore identifier, created with key
                          semkey, from the system and destroy the set of
                          semaphores and data structure associated with it.

      The details of the removals are described in msgctl(2), shmctl(2), and
      semctl(2).  The identifiers and keys can be found by using ipcs (see

 

by: sephiPosted on 2000-01-17 at 05:08:36ID: 2359111

I'm talking about a busy client/server environment. Multiple clients are communicating with multiple servers. If a client or a server process crashes, the resources must be automatically cleaned up.

If there is no way to tell the operating system to clean up, a daemon is needed to trace the IPC resources usage.

I was hoping to get a reference to such a daemon (preferably in C++).

 

by: kejinPosted on 2000-01-17 at 12:04:20ID: 2360443

How you define an IPC resource which can be removed? An IPC resource currently not being attached can be attached later. So, obviously, we can't simply remove IPC resources simply based on its current attach count.

 

by: sephiPosted on 2000-01-17 at 22:29:58ID: 2361702

You're right. The daemon must keep track of what resources are attached to which process. It has to detect crashed processes and remove their resources.

 

by: farajPosted on 2000-01-18 at 06:02:02ID: 2362813

There is an easy way to resolve the
 problem :
add these two lines before open the IPC resources :

// Place trap for  all crash
   for(i=1 ; i<19 ; i++)
      signal(i,&cleanup) ;




and define the function cleanup :


void cleanup()
{
//    Do cleanup (example for shared
//                mem)
      semctl(semid , IPC_RMID ,1) ;
      exit(-1) ;
}


This is the possibility .



 

by: rs_hebbarPosted on 2000-01-18 at 06:57:14ID: 2363013

I can think of 4 ideas
1. Write the programs such that  it does not dump core.
I think you should defenitely consider this option.
2. reboot the machine !!!!
3. If the process crash, have sigv handler, where you release the IPC resource ( I think this is a feasible solution)
4. In C++ , have a global exception handler, where you can handle these kind of exceptions.

 

by: kejinPosted on 2000-01-18 at 10:20:09ID: 2363833

to sephi:
Simply keeping track of attached processes doesn't tell you whether an IPC resource can be removed. A similar example is, if a process crashs, kernel will automatically close all its opened file descriptors but not files. Can you remove those files by simply keeping track of whethere it is opening by some processes? No! With same reason, an independent daemon can't remove an IPC resource by simply checking no process attaching to it. this is because, like files, IPC resource can be attached/used across process sessions. So, on crashing of a process, it is not kernel can't remove IPC resource but it doesn't want to.

The best solution for you is redesign your application to allow reuse or defered remove of those IPC resources instead of clean them immediately.

 

by: kejinPosted on 2000-01-18 at 10:21:16ID: 2363836

to faraj:

process may crash without going through your signal handle at all.

 

by: ufolk123Posted on 2000-01-18 at 20:20:19ID: 2365540

Hi ,

As I earlier said this is basic OS feature of Unix that it does not do reference counting
of resources like windows.So you do not have an option to detect what process is using which resource
Even kernal does not keep information about who has opened a resource and how many times.

So you have following basic options

1)If your apllication or set of application only are using a particular resource,
try to put the cleanup code in application startup.So when application is reinvoked it
will do cleanup for its previous instance.
2)Put the cleanup code in all signal handlers,anyway this will not help from crash.

If you are very keen to use a daemon.There is no default facility.For your need you may code
something like this.

Use a global table of resource information in a shared memory.Each record like
1)Resource Id
2)Global count of resource
3)liked list of resource data

each node of resource data
<process id of process who opened resource> <no of times opened (Referece count)>
For all resource creation/open calls use wrappers like
msgget->my_msgget
shmget->my_shmget etc

in all my_xxx do the following
1)open shared memeory
2)update/create resource data for this process.also update global count.
3)call actual msgget/shmget etc.


Create a process(daemon) doing the following
1)open the shared memory
2)while(1) do the following
3)for each resource check the validity of pid stored in resource data node.If process
referred by pid is dead update global count.(You may use pstat_getproc() routines or
/proc structure).
4)If global count dropped to zero ,remove the resource.
5)Sleep for some time.

Many points to take care
1)Sleeping period in daemon should be small so that pid values should not get reused in that period.
2)shared memory should be based on some ket which is globally accessible to both app & daemon

Hope this help you.If you have any doubts please feel free to express.

Regards,
ufolk123

 

by: sephiPosted on 2000-01-18 at 22:36:30ID: 2365769

I don't trust the signal control option proposed by faraj.

I prefer ufolk123's proposal to use a daemon.

I would like to understand, however, why the daemon needs to hold the resource list in shared memory?
Is it to protect against the daemon itself being crashed?

 

by: kejinPosted on 2000-01-18 at 23:17:47ID: 2365831

to ufolk123:

Unix kernel does reference count many of its resource usage include file descriptor, IPC objects, etc.. In IPC case, you can even see how many process is attached to an IPC resource using standardized API. The reference count will be reduced either the process released the reference (detached, closed, etc.) or the process crashed.

 

by: sephiPosted on 2000-01-19 at 00:13:39ID: 2365921

I know the ipcs command can show IPC usage. Is there an API for that? Does it show reference count?

 

by: kejinPosted on 2000-01-19 at 09:02:16ID: 2367594

It depends on which IPC resource. For share memory, you definitely can get the number of attached processes with shmctl()'s IPC_STAT option.

 

by: ufolk123Posted on 2000-01-19 at 21:20:48ID: 2369633

Hi,

regarding kejin's comment,there is no reference counting done for semaphores and message queues.Also shmctl IPC_STAT takes care of number of attch issued not the number of opens done by using shmget.So If a process just does shmget and dies without doing attach there is no way you can  trace it.

As par sephi's question i use shared memory or memory mapped files to keep track fo resource as daemon address space is differnt.As all apps need to register and daemon need to read the inofmration at a global place ,this is needed.There is other way of doing it using sending a resiteration messages and resource closes messages to daemon in that case we can use unix domain sockets/pipes for com between app and daemon and daemon can take care of resource list in a local heap.

Regards,
Rajesh

 

by: ufolk123Posted on 2000-01-19 at 21:26:45ID: 2369648

Hi Sephi,

finally we can say there are two alternatives to implement this daemon.

1)Use a shared memory to hold resource list.Each wrapper call(my_xxx) will access the shared memory ,update the info and daemon will poll on the shared memory.One semaphore (with UNDO option set)may be required for sync access to resource table.
2)Keep the table local to daemon.This way the wrapper calls will issue a message to a port being listened by daemon.This can be using a namedp pipe or unix domain socket conn opened for listening from daemon side.But this will have problems like comm traffic if number of client apps are many but in this case resource table is more safe(centerlised control).


Regards,
ufolk123

 

by: kejinPosted on 2000-01-19 at 22:32:05ID: 2369748

to ufolk123:

1. regarding to your statement of "there is no reference counting on semaphores and message queue", based on what? Can not get reference count via a public API doesn't means kernel doesn't do reference count. For instance, unix kernel does reference counting on file descriptor but there is no portable public API to find out what is the current count on a given fd. Also, for semaphores, you definitely can use semctl()'s IPC_STAT to get the number of processes waiting on a given semaphore. For mesage queue, this question doesn't make sense at first place. Because even a process crashed, the massage post by it before the crash shouldn't be removed and therefore neither the message queue itself.

2. regarding to your statement of "if a process only does a shmget() but not shmat(), there is no way you can trace it". This is exactly what my point. I.e. you can not based on the number of attached processes to decide whether  the IPC resource can be removed from the application point of view. Not only a process may only call shmget() but not shmat() immediately, a process can even not call shmget() at begining untill at a very later time when it needs to use the share memory segment. So, a daemon can't based on reference count or attach count on a share memory sagement to decide whether it is proper to remove it. So, even if the reference count or attach account are both zero, the daemon still has no way to know whether there is a process (either alive or not started yet) may get/attach this share memory segment later.

To all of us:
if installing signal handlers is an acceptable solution, then, the best solution is simply a atexit() handler.

 

by: ufolk123Posted on 2000-01-20 at 00:14:42ID: 2369930

Hi Kenji,

I fully agree with you that Unix does keep (a typical )refernce count for resources.
But my previous answer was focused at sephil's problem.

Consider the case1

Process 1 creates a semaphore using semget call.
Process 1 is crashed.
Now the semaphore will remain in the memory.But if had process1 been
terminated succesfully,he might had done a semctl.

Now consider case2

Process 1 creates a semaphore
Process 2 access the semaphore created by process1 using semget call.
Now even if either of Process1 or Process2 crashes semaphore should
not be removed unless until both logical owners of semaphore
(Process1 and Process2) are terminated.As any one of them can access
the semaphore by using desc returned by system.
So here comes the point.It is basically the acess function(which returns
a valid handle/descriptor to a resource) which should be useful
for reference counting for most cases.
As you know this is what is done by Windows and i feel should
work for catering the need of an application dev.

I do not want to prove that Unix does not do any logical ref counting
But it does not solve the common nightmare of developers where when
all logical owners of a resource are terminated but nobody issued
the ctl commnad, resource is not reclaimed.

I feel sorry if i sounded like a critique to you in my previous answer.

Regards,
ufolk123

 

by: kejinPosted on 2000-01-20 at 09:48:13ID: 2371591

As I said many times that, unix kernel, which doesn't remove IPC resources in above case, isn't b/c it is incapable to do so but it doesn't want to. The IPC resources are allowed to be used across process sessions. For example, a process can create an IPC resource and terminate without have to bring do the created IPC resource with it when no any other processes using it. Then, long time after the original creator teriminate, another process may start and get this IPC resource. So, during this long time window, there is no any process refering to this IPC resources (i.e. its reference count is 0). I am not very formula with windows but please understand above unix ipc behavior isn't a "problem" but a feature. Just like a normal unix file lives accross kernel session, IPC resources live across user process sessions by design. If developers feel this is a nightmare comparing to what they enjoy in windows world, they should, as I suggested in  one of previous comment, redesign their applications.

You don't need bother to prove unix doesn't do logical ref counting. It is well documented that unix kernel does reference count on file descriptors.

 

by: farajPosted on 2000-01-23 at 14:09:20ID: 2379737

If you doesn't like the proposition
to use signal trap
Another solution using fork is to run all the program in the sons. The father is looking
for the exit status. If the exit status is not 0, the father will clean
son's resources.

Regards ,
 Faraj.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...