3 ms·
In essence this is manually implementing forking — spawning a new process and copying the bytes over without getting the kernel to help you, except over a netwo
by TazeTSchnitzel 7y ago
In essence this is manually implementing forking — spawning a new process and copying the bytes over without getting the kernel to help you, except over a network too.
It reminds me a bit of when I wanted to parallelise the PHP test suite but didn't want to (couldn't?) use fork(), yet I didn't want to substantially rewrite the code to be amenable to cleanly re-initialising the state in the right way. But conveniently, this program used mostly global variables, and you can access global variables in PHP as one magic big associative array called $GLOBALS. So I moved most of the program's code into two functions (mostly just adding the enclosing function declaration syntax and indentation, plus `global` imports), made the program re-invoke itself NPROCS times mid-way, sending its children `serialize($GLOBALS)` over a loopback TCP connection, then had the spawned children detect an environment variable to receieve the serialized array over TCP, unserialize() it and copy it into `$GLOBALS`, and call the second function… lo and behold, it worked perfectly. :D (Of course I needed to make some other changes to make it useful, but they were also similar small incisions that tried to avoid refactoring the code as much as possible.)
PHP's test suite uses this horrible hack to this day. It's… easier than rewriting the legacy code…
- trishume 7y agoIndeed! I was talking to someone about their attempt to fork a Graal Java process and recreate all the compiler and GC threads, and I said if I had that task I'd be tempted to just use my new knowledge to implement a fork that also recreated those threads rather than trying to understand how to shut them down and restore them properly.
- i15e 7y agoI did something similar using the 'at' daemon's 'now' time specification to "fork" off background tasks from a web request using the same .php file. It actually worked well for what I needed at the time!