Advertisement
Guest User

Untitled

a guest
Jul 6th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. <?php
  2.  
  3. fork_process(
  4. $start = 1,
  5. $end = 10,
  6. $function_name = 'run',
  7. $block_size = 1,
  8. $processes = 4
  9. );
  10.  
  11. function fork_process($start, $end, $function_name, $block_size, $processes) {
  12. $from = $start;
  13. $to = $block_size;
  14.  
  15. $block = ceil((($end - $start)) / $block_size);
  16.  
  17. $sockets = array();
  18. if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
  19. echo socket_strerror(socket_last_error())."\n";
  20. exit(0);
  21. }
  22.  
  23. $index = 0;
  24.  
  25. $parent = true;
  26. $children = array();
  27. for ($i = 0; $i < min($processes, $block) && $parent; $i++) {
  28. $pid = pcntl_fork();
  29. if ($pid == 0) {
  30. $parent = false;
  31. $index = $i;
  32. sleep(1);
  33. } else if ($pid != -1) {
  34. $children[] = $pid;
  35. }
  36. }
  37.  
  38. if ($parent) {
  39. process_parent($sockets, $children, $block, $block_size, $function_name, $end, $start, $processes);
  40. } else {
  41. $from = $start + ($block_size * $index);
  42. $to = $start + ($block_size * ($index + 1)) - 1;
  43. if ($end <= $to) {
  44. $to = $end;
  45. }
  46.  
  47. process_child($sockets, $index, $from, $to, $function_name);
  48. posix_kill(getmypid(), 9);
  49. }
  50. }
  51.  
  52. function process_parent(&$sockets, &$children, $block, $blockSize, $functionName, $maxId, $start, $processNum) {
  53. $parent = true;
  54.  
  55. $status = null;
  56. while (count($children)) {
  57. pcntl_wait($status);
  58. array_pop($children);
  59. socket_set_nonblock($sockets[0]);
  60. $output = socket_read($sockets[0], 100000, PHP_BINARY_READ);
  61. if ($output === false) {
  62. echo socket_strerror(socket_last_error($sockets[0]))."\n";
  63. continue;
  64. } else {
  65. // process output from children
  66. }
  67. }
  68. socket_close($sockets[0]);
  69. }
  70.  
  71. function process_child(&$sockets, $index, $from, $to, $functionName) {
  72. socket_close($sockets[0]);
  73. $data = call_user_func_array($functionName, array($from, $to));
  74. if (socket_write($sockets[1], $data) === false) {
  75. echo socket_strerror(socket_last_error($sockets[1]))."\n";
  76. }
  77. socket_close($sockets[1]);
  78. }
  79.  
  80. function run() {
  81. return true;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement