protected function cleanup()
    {
        if ($this->running) {
            throw new RuntimeException(sprintf('Cleanup error - process still running: %s', is_scalar($this->command) ? $this->command : $this->command->serialize()));
        }

        if (!isset($this->resource)) {
            return;
        }

        $this->pid = -1;
        $this->read();

        foreach ($this->pipes as $index => $pipe) {
            if (!$this->interactive && $index === static::STDIN) {
                continue;
            }

            fclose($pipe);
        }

        proc_close($this->resource);
        unset($this->resource, $this->pipes);

        $this->running = false;

        if (in_array($this->exitcode, $this->getExpectedExitcodes())) {
            if (isset($this->onSuccess)) {
                call_user_func($this->onSuccess);
            }
        } else {
            if (isset($this->onError)) {
                call_user_func($this->onError, $this);
            } else {
                throw new ProcessException(sprintf('Error executing process: %s', is_scalar($this->command) ? $this->command : $this->command->serialize()), $this);
            }
        }
    }