kyle has asked for the wisdom of the Perl Monks concerning the following question:
I was thinking this morning that it would be nice to have a way to run some sub in a forked process and get its normal return value back without having to think about it too much. I can think of two ways I might want to do this.
- fork and wait because I want to leak memory somewhere else, but I don't want to run in parallel. This could even be a simple wrapper like what Memoize does.
- Run a sub in parallel and collect the return value from it when it's done.
I went looking around CPAN, and I found a few things that are similar but not quite what I had in mind.
- Parallel::SubFork won't give me the return value.
- Parallel::Forker also won't give me the return value.
- Proc::Forkfunk expects the sub never to return.
- Acme::Fork::Lazy can only return scalars, and it won't let me ask it if something's done—just ask for the result and block if it's not ready.
Is there a module that does what I want? I want to hand it a sub reference for it to call after a fork, and I want to get back whatever the sub would have returned if I'd called it directly (within understandable limits).
Not finding this, I started thinking about the interface I'd want and how to handle special cases.
- Do I clobber the "$SIG{CHLD}" of my caller? I guess I'd make that optional.
- What if the sub throws an exception? I guess I'd throw it at the caller when it requests its return value.
- What if the sub calls exit?
- I'd have to get the return value back via pipe. Is that going to step on something in the child?
- Do I need to take care of cleaning up open files the parent had before the fork? How about database handles? Maybe I just need a hook for something to call after the fork but before the target sub.
- How much of the sub's context should I simulate? If I'm given a sub in one place and the return value is collected much later, I won't know the context when I need to. I guess I have to make the caller tell me the context ahead of time and create a reasonable default.
My questions are does this already exist? and if not, what features would you want from a new implementation?
Update: Thanks to Corion (in Re^5: Module for transparently forking a sub?), I have seen the light of forks, which is just what I was looking for. Thanks!