A real fork() call could be possible on Windows (XP onwards)
Prompted by BrowserUk in his post on Perlmonks on Win32, fork and XS globals, I looked into the PAGE_WRITECOPY
for CreateFileMapping, and it seems that, in fact, this function, together with a bit of work could be made to implement a (data-)fork call on Windows, with real sharing of identical pages.
There is this sample program on the MSDN, which outlines how to use a mapped view of a file for shared memory IPC, and by using the PAGE_WRITECOPY
flag instead of FILE_MAP_ALL_ACCESS
, we should get COW semantics for the shared area.
The part for implementing fork() would seem to just be:
- (and that is the hard part) Determine the range of data to be shared with the child
- CreateFileMapping in the parent process to share the area from 0.
- MapViewOfFile
- Launch the child process
- In the child process, call
OpenFileMapping()
to connect to the data area from the parent process. - Fix up any cached values that need changing after a fork(), for example
$$
I think
$$
was only recently changed to no longer be cached.And this is incomplete in other ways. What about the parent’s environment? Its open file handles? I’m sure there are a couple more things.
But it may well be possible to tick all the boxes. It’ll just take more work to emulate
fork
sufficiently completely.I think this could be prototyped as an XS module?
I don’t know if the proposal of not caching
$$
went in already :)Spawning the child process will automatically make it inherit the environment and the open (file) handles. That already works well with
system()
too.I’m not sure that this can live in an XS module, as the area to-be-shared needs to be fenced off before allocating memory in it (I think), so you can’t retroactively tell Windows “Oh – and please make $lowmem..$highmem shareable”. But once I find enough time, that can be investigated.
At least the hard problem of convincing the OS to do COW seems to be solved…