0

I am trying to release resources allocated in daemon process at the end of it or if someone quits the process.

Lets say,

int main(int argc, const char * argv[])
{
    Controller *controller = [[Controller alloc] init];
    [controller allocateresources];

    [[NSRunLoop currentRunLoop] run];

    [controller release];

    return 0;
}

Here Controller release will not be called. Quit [SIGTERM Signal] just terminates the runloop. How can I release resources allocated in class Controller at the end of application?

EDIT: I understand that system will claim resources back. The thing, I am trying to solve is something like cross process cooperative locks.

RLT
  • 4,219
  • 4
  • 37
  • 91
  • If the app is ending you really don't need to worry about releasing anything as the system will reclaim everything from the app. But normally you would create and call a dealloc method. (using MRC instead of ARC) as for the runloop, you can also use autorelease. – uchuugaka Apr 04 '13 at 12:00
  • @uchuugaka I tried to use autorelease pool. It does not call dealloc method. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Controller *controller = [[[Controller alloc] init] autorelease]; [[NSRunLoop currentRunLoop] run]; [pool drain]; – RLT Apr 04 '13 at 12:17
  • How is the process being quit? If you're just sending SIGTERM, then you could add a signal handler. – Ken Aspeslagh Apr 04 '13 at 13:53
  • I was looking to manage all cases, including crash. – RLT Apr 04 '13 at 15:16

1 Answers1

2

I don't think there is really a guarantee that you will return from the -run method. So you shouldn't rely on this to free the resources. There are other ways to do it. For example, a really low-level solution would be to implement an atexit handler

https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/atexit.3.html

and do the necessary freeing of the lock there.

ashcatch
  • 2,327
  • 1
  • 18
  • 29
  • Before looking at this method (by referring your answer), I implemented Unix signal handlers to do clean up. Which approach do you think is cleaner? – RLT Apr 04 '13 at 15:16
  • Signal handlers work only for certain signals. I think the atexit handler works for almost all ways how the application is quit. The only exception where the atexit handler is not called is if the program was quit with _exit(). – ashcatch Apr 04 '13 at 15:20
  • Thanks. This method is perfect for me and much cleaner. – RLT Apr 04 '13 at 15:31