If you don't pass the CLONE_VM flag to clone(), then the new process shares memory with the original. Can this be used to make two distinct applications (two main()'s) run in the same process? Ideally this would be as simple as calling clone() with CLONE_VM and then calling exec(), but I realize it's probably more involved. At the very least, I assume that the spawned application would need to be compiled to be relocatable (-fPIC). I realize I could always recode applications to be libraries, and create a master app spawning the other 'apps' as threads, but I'm curious of this approach is possible.

3 Answers
3

Well, it's possible if you're willing to write your own custom ELF loader and simulate a lot of things that the kernel normally does for a process.

It's better to compile each of the apps into a library that exposes exactly one function, main (renamed to something else). Then the main stub program should link with the two libraries and call each one's exported function.

Imagine you have two old crufty pieces of software and they're filled with overlapping global variable names or functions. Trying to compile them into the same app will cause errors.
–
Joseph GarvinOct 30 '09 at 12:46

Actually, better example: You realize that when you run two applications together context switching becomes a bottleneck. So you want to run two apps in the same address space so the TLB doesn't have to be swapped out.
–
Joseph GarvinOct 30 '09 at 12:54

Is this context switching actually becoming a bottleneck? Have you tried it on a machine with more cores? Most have at least two nowadays.
–
MarkROct 30 '09 at 13:59

Clone(2) more-or-less requires you to declare a separate stack (if you don't it makes one), because without it the child won't be able to return from its current call level without destroying the parent's stack.

Once you start setting up stacks for each process then you might as well just use the posix thread library.

As for the part where two different applications are loaded, calling execve(2) would most likely not be the way to do it. These days the kernel doesn't precisely run programs anyway. It's more typical that the image is set up to run the Elf dynamic loader, and that's all that the kernel really runs. The loader then mmaps(2)s the process and its libraries into the address space. Certainly that could be done to get the "two distinct applications", and the thread scheduler would be happy to run them as two processes via clone(2).