3 namespace Thrift\Server
;
5 use Thrift\Transport\TTransport
;
6 use Thrift\Exception\TException
;
7 use Thrift\Exception\TTransportException
;
10 * A forking implementation of a Thrift server.
12 * @package thrift.server
14 class TForkingServer
extends TServer
17 * Flag for the main serving loop
21 private $stop_ = false;
28 protected $children_ = array();
31 * Listens for new client using the supplied
32 * transport. We fork when a new connection
37 public function serve()
39 $this->transport_
->listen();
41 while (!$this->stop_
) {
43 $transport = $this->transport_
->accept();
45 if ($transport != null) {
49 $this->handleParent($transport, $pid);
50 } elseif ($pid === 0) {
51 $this->handleChild($transport);
53 throw new TException('Failed to fork');
56 } catch (TTransportException
$e) {
59 $this->collectChildren();
64 * Code run by the parent
66 * @param TTransport $transport
70 private function handleParent(TTransport
$transport, $pid)
72 $this->children_
[$pid] = $transport;
76 * Code run by the child.
78 * @param TTransport $transport
81 private function handleChild(TTransport
$transport)
84 $inputTransport = $this->inputTransportFactory_
->getTransport($transport);
85 $outputTransport = $this->outputTransportFactory_
->getTransport($transport);
86 $inputProtocol = $this->inputProtocolFactory_
->getProtocol($inputTransport);
87 $outputProtocol = $this->outputProtocolFactory_
->getProtocol($outputTransport);
88 while ($this->processor_
->process($inputProtocol, $outputProtocol)) {
91 } catch (TTransportException
$e) {
98 * Collects any children we may have
102 private function collectChildren()
104 foreach ($this->children_
as $pid => $transport) {
105 if (pcntl_waitpid($pid, $status, WNOHANG
) > 0) {
106 unset($this->children_
[$pid]);
108 @$transport->close();
115 * Stops the server running. Kills the transport
116 * and then stops the main serving loop
120 public function stop()
122 $this->transport_
->close();