Tuesday, March 28, 2006

fork + execve - so happy together!

A long time ago in the 70s when everyone smoked a lot of dope, someone thought it would be cute to break the application launch APIs into two pieces. First you call fork to clone yourself (but this is really fast because the OS is lazy) and then execve turns one copy into something new. Cute!

I just learned two interesting things about Mac OS X tonight:

1. Apparently fork without execve won’t always work.

2. execve without fork doesn’t work so well either.

In the first case, you can read here about why forking doesn’t always work. In Apple’s defense, I don’t blame them for this - fork is supposed to be fast, and cloning all of the apps resources wouldn’t be. Oh yeah, some of those resources might be owned in some exclusive mode. Historically fork was a way to use processes like threads. Or are threads processes? I don’t know…it’s 2:30 AM and my brain hurts.

In the second case, frankly I have no idea why execve won’t work on its own. I get error 45:

#define ENOTSUP 45 /* Operation not supported */

My speculation is that execve requires a “clean” process of some type, e.g. a forked process and not a regular one.

Either way the moral of the story is clear: apparently no one has tried to use these two functions separately since they made disco illegal, so neither should you. Fork even if you don’t need to, then kill off the parent.

2 comments:

  1. If you think about it some stuff doesn't make any sense with fork... like GUI apps (think about apps on linux with an X GUI... what happens to that when you fork...)

    Basically if there is state outside the process that is not file descriptors or something that the kernel knows about and can clone then it doesn't get copied (and really why would you want to fork such an app...)

    ReplyDelete
  2. the real issue is expecting things from fork it never promised...

    besides fork has always been something you need to be careful with and make sure you know what you're doing and what it gives you.

    ie it is still a reasonable thing to write a pre-forking (or just a forking) server of some kind (ie webserver), sure threads are faster, but forking gets you free cleanups every so often so your bugs are less severe (like memory leaks or crashes)

    If all you expect to get cloned is your memory and file descriptors then fork works, if you have some other state outside your app you need to deal with it yourself.

    OSX's issue seems to be that some Apple libraries unexpectedly (at least for some people) have state out side the process using them that does not get copied by fork.

    ReplyDelete