Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- fork_process(
- $start = 1,
- $end = 10,
- $function_name = 'run',
- $block_size = 1,
- $processes = 4
- );
- function fork_process($start, $end, $function_name, $block_size, $processes) {
- $from = $start;
- $to = $block_size;
- $block = ceil((($end - $start)) / $block_size);
- $sockets = array();
- if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
- echo socket_strerror(socket_last_error())."\n";
- exit(0);
- }
- $index = 0;
- $parent = true;
- $children = array();
- for ($i = 0; $i < min($processes, $block) && $parent; $i++) {
- $pid = pcntl_fork();
- if ($pid == 0) {
- $parent = false;
- $index = $i;
- sleep(1);
- } else if ($pid != -1) {
- $children[] = $pid;
- }
- }
- if ($parent) {
- process_parent($sockets, $children, $block, $block_size, $function_name, $end, $start, $processes);
- } else {
- $from = $start + ($block_size * $index);
- $to = $start + ($block_size * ($index + 1)) - 1;
- if ($end <= $to) {
- $to = $end;
- }
- process_child($sockets, $index, $from, $to, $function_name);
- posix_kill(getmypid(), 9);
- }
- }
- function process_parent(&$sockets, &$children, $block, $blockSize, $functionName, $maxId, $start, $processNum) {
- $parent = true;
- $status = null;
- while (count($children)) {
- pcntl_wait($status);
- array_pop($children);
- socket_set_nonblock($sockets[0]);
- $output = socket_read($sockets[0], 100000, PHP_BINARY_READ);
- if ($output === false) {
- echo socket_strerror(socket_last_error($sockets[0]))."\n";
- continue;
- } else {
- // process output from children
- }
- }
- socket_close($sockets[0]);
- }
- function process_child(&$sockets, $index, $from, $to, $functionName) {
- socket_close($sockets[0]);
- $data = call_user_func_array($functionName, array($from, $to));
- if (socket_write($sockets[1], $data) === false) {
- echo socket_strerror(socket_last_error($sockets[1]))."\n";
- }
- socket_close($sockets[1]);
- }
- function run() {
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement