Reads pipes for the freshest output.

@param string $caller   The name of the method that needs fresh outputs
@param bool   $blocking Whether to use blocking calls or not

@throws LogicException in case output has been disabled or process is not started
971049
private function readPipesForOutput($caller, $blocking = false)
    {
        if ($this->outputDisabled) {
            throw new LogicException('Output has been disabled.');
        }

        $this->requireProcessIsStarted($caller);

        $this->updateStatus($blocking);
    }
944558
public function beforeCompile(): void
	{
		$builder = $this->getContainerBuilder();

		if ($builder->getByType(Application::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', Application::class));
		}

		if ($builder->getByType(EventDispatcherInterface::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', EventDispatcherInterface::class));
		}

		$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcherInterface::class));

		$application = $builder->getDefinition($builder->getByType(Application::class));

		$application->addSetup('?->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_STARTUP,
			new PhpLiteral(StartupEvent::class),
		]);

		$application->addSetup('?->onError[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_ERROR,
			new PhpLiteral(ErrorEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER,
			new PhpLiteral(PresenterEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function($application, $presenter) {if(!property_exists($presenter, "onStartup")){return;} $presenter->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));};}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER_STARTUP,
			new PhpLiteral(PresenterStartupEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function($application, $presenter) {if(!property_exists($presenter, "onShutdown")){return;} $presenter->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));};}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER_SHUTDOWN,
			new PhpLiteral(PresenterShutdownEvent::class),
		]);

		$application->addSetup('?->onRequest[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_REQUEST,
			new PhpLiteral(RequestEvent::class),
		]);

		$application->addSetup('?->onResponse[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_RESPONSE,
			new PhpLiteral(ResponseEvent::class),
		]);

		$application->addSetup('?->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_SHUTDOWN,
			new PhpLiteral(ShutdownEvent::class),
		]);
	}
329298
public function disableOutput()
    {
        if ($this->isRunning()) {
            throw new RuntimeException('Disabling output while the process is running is not possible.');
        }
        if (null !== $this->idleTimeout) {
            throw new LogicException('Output can not be disabled while an idle timeout is set.');
        }

        $this->outputDisabled = true;

        return $this;
    }
612288
public function load($object)
    {
        if (get_class($object) !== $this->objectClass) {
            throw new \LogicException(sprintf('Invalid object type. Expected "%s" but got "%s".', $this->objectClass, get_class($object)));
        }

        $hydrator = $this->objectManager->getHydratorFor($this->objectClass);
        $hydrator->load($object);
    }
846634
public function start()
    {
        if (!empty($this->pid) && $this->isRunning()) {
            throw new \LogicException("the process is already running");
        }

        $callback = $this->getCallable();

        $pid = pcntl_fork();
        if ($pid < 0) {
            throw new \RuntimeException("fork error");
        } elseif ($pid > 0) {
            $this->pid = $pid;
            $this->running = true;
            $this->started = true;
        } else {
            $this->pid = getmypid();
            $this->signal();
            foreach ($this->signal_handlers as $signal => $handler) {
                pcntl_signal($signal, $handler);
            }
            call_user_func($callback);
            exit(0);
        }
    }
805536
public function block($name)
    {
        $this->currentBlock = $name;

        $this->getBlockQueue()->push($name);

        // Start an output buffer.
        ob_start();
    }
1033703
public function get($block = false)
    {
        if ($this->block != $block) {
            $this->pipe->setBlock($block);
            $this->block = $block;
        }
        $len = $this->pipe->read(4);
        if ($len === false) {
            throw new \RuntimeException('read pipe failed');
        }

        if (strlen($len) === 0) {
            return null;
        }
        $len = unpack('N', $len);
        if (empty($len) || !array_key_exists(1, $len) || empty($len[1])) {
            throw new \RuntimeException('data protocol error');
        }
        $len = intval($len[1]);

        $value = '';
        while (true) {
            $temp = $this->pipe->read($len);
            if (strlen($temp) == $len) {
                return $temp;
            }
            $value .= $temp;
            $len -= strlen($temp);
            if ($len == 0) {
                return $value;
            }
        }
    }
403855
function setBlocking (blocking) {
  [process.stdout, process.stderr].forEach(stream => {
    /* istanbul ignore else */
    if (stream._handle && typeof stream._handle.setBlocking === 'function') {
      stream._handle.setBlocking(blocking)
    }
  })
}
1285918
private function printBlock($block)
    {
        if (!array_key_exists($block, $this->blocks)) {
            throw new \Exception('Block '.$block.' not defined');
        }
        $this->finishBlock($block);

        $output = "";
        $output .= "    $block";
        $output .= " (".$this->blocks[$block]['start-line']."-".$this->blocks[$block]['stop-line'].")";
        $output .= ": ";
        $output .= round($this->blocks[$block]['total'], 4);
        $output .= ' seconds';
        $output .= PHP_EOL;

        return $output;
    }
10242
protected function blockLines(OutputBlock $block)
    {
        $inner = $this->indentStr();

        $glue = $this->break . $inner;

        $this->write($inner . implode($glue, $block->lines));

        if (! empty($block->children)) {
            $this->write($this->break);
        }
    }
1052529
private function readDocBlockCallees($class, ReflectionMethod $method, $docBlock)
    {
        $callees = array();
        $description = $this->readDescription($docBlock);
        $docBlock = $this->mergeMultilines($docBlock);

        foreach (explode("\n", $docBlock) as $docLine) {
            $docLine = preg_replace(self::DOCLINE_TRIMMER_REGEX, '', $docLine);

            if ($this->isEmpty($docLine)) {
                continue;
            }

            if ($this->isNotAnnotation($docLine)) {
                continue;
            }

            if ($callee = $this->readDocLineCallee($class, $method, $docLine, $description)) {
                $callees[] = $callee;
            }
        }

        return $callees;
    }
398570
public function doLock($blocking = false)
    {
        if ($this->lockAcquired) {
            return $this;
        }

        $this->mode   = $this->mode ?: (is_file($this->file) ? 'rb' : 'wb');
        $this->handle = fopen($this->file, $this->mode) ?: null;
        if (
            $this->lockType === self::LOCK_EXTERNAL &&
            $this->mode === 'wb' &&
            !$this->handle
        ) {
            // if another process won the race at creating lock file
            $this->mode   = 'rb';
            $this->handle = fopen($this->file, $this->mode) ?: null;
        }

        $this->lockAcquired = $this->handle ? flock($this->handle, $blocking ? LOCK_EX : LOCK_EX | LOCK_NB) : false;

        if (!$this->lockAcquired) {
            $this->unLock();
        }

        return $this;
    }
746903
public function execute(InputInterface $input, OutputInterface $output)
    {
        if (! $this->emailSender) {
            throw new LogicException('No email sender configured (did you set the API key?)');
        }

        if (! $this->emailMapper) {
            throw new LogicException('No email mapper configured');
        }

        $output->writeln('Finding email by ID');

        $emailId = $input->getArgument('id');

        $email = $this->emailMapper->findById($emailId);

        if (!$email or $email->isNew()) {
            throw new OutOfBoundsException('Email not found.');
        }

        $output->writeln('Sending email');

        list($email, $result) = $this->emailSender->send($email);

        if ($email->getStatus() !== EmailEntity::STATUS_SENT) {
            $format = 'Email did NOT send successfully. Returned with status %s.';
            $message = sprintf($format, $result['status']);

            if (isset($result['reject_reason'])) {
                $message .= ' Reason rejected: '.$result['reject_reason'];
            }

            $output->writeln($message);

            return 500;
        }

        $output->writeln('Email sent successfully!');
    }
211071
private static function createOnBlockHandler(LoggerInterface $logger): callable
    {
        return static function(int $blockInterval) use ($logger): void
        {
            $trace     = \debug_backtrace();
            $traceData = ['info' => []];

            /** skip first since it's always the current method */
            \array_shift($trace);
            /** the call_user_func call is also skipped */
            \array_shift($trace);

            $i = 0;

            while (isset($trace[$i]['class']))
            {
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $traceData['info'] = \array_merge(
                    $traceData['info'],
                    [
                        'file'     => $trace[$i - 1]['file'] ?? null,
                        'line'     => $trace[$i - 1]['line'] ?? null,
                        'class'    => $trace[$i]['class'] ?? null,
                        'function' => $trace[$i]['function'] ?? null,
                    ]
                );

                $i++;
            }

            $traceData['lockTime'] = 0 !== $blockInterval ? $blockInterval / 1000 : 0;

            $logger->error('A lock event loop has been detected. Blocking time: {lockTime} seconds', $traceData);

            unset($traceData, $trace, $i);
        };
    }
46011
public function acquire($blocking = true)
    {
        if ($this->locked) {
            throw new \RuntimeException('already lock by yourself');
        }

        if ($blocking) {
            $locked = flock($this->fp, LOCK_EX);
        } else {
            $locked = flock($this->fp, LOCK_EX | LOCK_NB);
        }

        if ($locked !== true) {
            return false;
        }
        $this->locked = true;

        return true;
    }
206683
@Override
    public int checkStillBlocked()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "checkStillBlocked");

        int blockingReason = DestinationHandler.OUTPUT_HANDLER_FOUND;

        boolean isBlocked = !_itemStream.isQLowRemoteLimit();
        if (isBlocked)
            blockingReason = DestinationHandler.OUTPUT_HANDLER_ALL_HIGH_LIMIT;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "checkStillBlocked", Integer.valueOf(blockingReason));
        return blockingReason;

    }
1368173
protected function process_file_block($block, tgz_extractor_handler $handler = null) {
        // Write block into buffer.
        $blocksize = tgz_packer::TAR_BLOCK_SIZE;
        if ($this->currentfileprocessed + tgz_packer::TAR_BLOCK_SIZE > $this->currentfilesize) {
            // Partial block at end of file.
            $blocksize = $this->currentfilesize - $this->currentfileprocessed;
            $this->filebuffer .= substr($block, 0, $blocksize);
        } else {
            // Full-length block.
            $this->filebuffer .= $block;
        }
        $this->filebufferlength += $blocksize;
        $this->currentfileprocessed += $blocksize;

        // Write block to file if necessary.
        $eof = $this->currentfileprocessed == $this->currentfilesize;
        if ($this->filebufferlength >= self::WRITE_BLOCK_SIZE || $eof) {
            // Except when skipping the file, write it out.
            if ($this->currentfile !== true) {
                if (!fwrite($this->currentfp, $this->filebuffer)) {
                    throw new moodle_exception('errorprocessingarchive', '', '', null,
                            'Failed to write buffer to output file: ' . $this->currentfile);
                }
            }
            $this->filebuffer = '';
            $this->filebufferlength = 0;
        }

        // If file is finished, close it.
        if ($eof) {
            $this->close_current_file($handler);
        }
    }