Heinzi
Heinzi

Reputation: 6093

fork() and free all allocated memory

I'm writing a service (i.e. background process) and want to offer starting it via a shared library. That is, someone wanting to use the service would link to the shared library, call it's start() method, which would fork and return. The fork would then run the service.

The problem with this approach is that the service process now might have a lot of legacy allocated memory it actually doesn't need. Is there a way to get rid of that and have the forked process allocate its own stuff? I know about exec() of course, but the problem with that is

So basically, I'm looking for a way to call an arbitrary function func() with some parameters that should run in a new process, and everything not passed into that function shouldn't be in the new process. Is there a way to achieve this or something similar?

Upvotes: 0

Views: 664

Answers (1)

that other guy
that other guy

Reputation: 123490

This is an interesting question that I sadly don't have a good answer for. I doubt any cleanup strategies like sbrk+close+munmap will reliably allow any libc based code to continue to function, so I'd try to make exec'ing better:

For any kind of exec based solution, you should be able to deep-copy data into shm to pass non-strings. This should take care of your second problem.

Here are some wild suggestions for your first issue:

  1. Don't: just require that an executable is in PATH or a compile-time directory.

    This is transparent and follows the UNIX philosophy. An error message Can't find myhelper in PATH will not slow anyone down. Most tools depending on helper executables do this, and it's fine.

  2. Make your library executable, and use that as your exec target. You can try finding its name with some kind of introspection, perhaps /proc/self/maps or whatever glibc offers.

  3. Like above, but exec python or something you can be reasonably sure exists, and use a foreign pointer interface to run a function on your library.

  4. As part of your build process, compile a tiny executable and include it as binary data in your library. Write it to /tmp and execute.

Out of these, I prefer the simplicity and transparency of #1, even if that's the most boring solution.

Upvotes: 3

Related Questions