本文整理汇总了PHP中socket_create_pair函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_create_pair函数的具体用法?PHP socket_create_pair怎么用?PHP socket_create_pair使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了socket_create_pair函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: countFiles
public function countFiles(array $files, $countTests)
{
$chunkSize = ceil(count($files) / $this->_cores);
$chunks = array_chunk($files, $chunkSize);
$forks = array();
$sockets = array();
for ($i = 0; $i < $this->_cores; $i++) {
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
echo "socket_create_pair failed. Reason: " . socket_strerror(socket_last_error());
}
$this->socketPairs[] = $sockets;
$forks[] = $pid = pcntl_fork();
if ($pid === 0) {
parent::countFiles($chunks[$i], $countTests);
$data = array('count' => $this->count, 'namespaces' => $this->namespaces);
$dataString = serialize($data);
socket_set_nonblock($sockets[0]);
if (socket_write($sockets[0], str_pad($dataString, self::MESSAGE_LENGTH), self::MESSAGE_LENGTH) === false) {
throw new Exception("socket_write() failed. Reason: " . socket_strerror(socket_last_error($sockets[0])));
}
socket_close($sockets[0]);
die;
}
}
do {
pcntl_wait($status);
array_pop($forks);
} while (count($forks) > 0);
for ($i = 0; $i < $this->_cores; $i++) {
$sockets = $this->socketPairs[$i];
$childMessage = '';
$childMessage = socket_read($sockets[1], self::MESSAGE_LENGTH);
$data = unserialize(trim($childMessage));
socket_close($sockets[1]);
$this->mergeAndSumCount($data['count']);
$this->mergeNamespaces($data['namespaces']);
// $this->mergeDirectories($data['directories']);
}
// need to find some way to pass the number of directories from the child to the paent so
// we don't have to do this again
// same with namespaces which are also a object variable
$count = $this->getCount($countTests);
foreach ($files as $file) {
$directory = dirname($file);
if (!isset($directories[$directory])) {
$directories[$directory] = TRUE;
}
}
$count['directories'] = count($directories) - 1;
return $count;
}
示例2: async
function async($thunk)
{
// By creating a socket pair, we have a channel of communication
// between PHP processes
socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets);
list($parent, $child) = $sockets;
if (($pid = pcntl_fork()) == 0) {
// We're in the child process now
socket_close($child);
// Call the thunk, serialize the returned value, and send it
// through the channel we created (ie. to the parent process)
socket_write($parent, serialize(call_user_func($thunk)));
socket_close($parent);
exit;
// We're done so we can exit here
}
socket_close($parent);
return array($pid, $child);
// This can treated as a "thread handle"
}
示例3: pleac_Communicating_Between_Related_Processes
function pleac_Communicating_Between_Related_Processes()
{
// PHP supports fork/exec/wait but not pipe. However, it does
// support socketpair, which can do everything pipes can as well
// as bidirectional communication. The original recipes have been
// modified here to use socketpair only.
// -----------------------------
// pipe1 - use socketpair and fork so parent can send to child
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($reader, $writer) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($reader);
$line = sprintf("Parent Pid %d is sending this\n", getmypid());
if (!socket_write($writer, $line, strlen($line))) {
socket_close($writer);
die(socket_strerror(socket_last_error()));
}
socket_close($writer);
pcntl_waitpid($pid, $status);
} else {
socket_close($writer);
$line = socket_read($reader, 1024, PHP_NORMAL_READ);
printf("Child Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($reader);
// this will happen anyway
exit(0);
}
// -----------------------------
// pipe2 - use socketpair and fork so child can send to parent
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($reader, $writer) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($writer);
$line = socket_read($reader, 1024, PHP_NORMAL_READ);
printf("Parent Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($reader);
pcntl_waitpid($pid, $status);
} else {
socket_close($reader);
$line = sprintf("Child Pid %d is sending this\n", getmypid());
if (!socket_write($writer, $line, strlen($line))) {
socket_close($writer);
die(socket_strerror(socket_last_error()));
}
socket_close($writer);
// this will happen anyway
exit(0);
}
// -----------------------------
// pipe3 and pipe4 demonstrate the use of perl's "forking open"
// feature to reimplement pipe1 and pipe2. pipe5 uses two pipes
// to simulate socketpair. Since PHP supports socketpair but not
// pipe, and does not have a "forking open" feature, these
// examples are skipped here.
// -----------------------------
// pipe6 - bidirectional communication using socketpair
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
die(socket_strerror(socket_last_error()));
}
list($child, $parent) = $sockets;
$pid = pcntl_fork();
if ($pid == -1) {
die('cannot fork');
} elseif ($pid) {
socket_close($parent);
$line = sprintf("Parent Pid %d is sending this\n", getmypid());
if (!socket_write($child, $line, strlen($line))) {
socket_close($child);
die(socket_strerror(socket_last_error()));
}
$line = socket_read($child, 1024, PHP_NORMAL_READ);
printf("Parent Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
socket_close($child);
pcntl_waitpid($pid, $status);
} else {
socket_close($child);
$line = socket_read($parent, 1024, PHP_NORMAL_READ);
printf("Child Pid %d just read this: `%s'\n", getmypid(), rtrim($line));
$line = sprintf("Child Pid %d is sending this\n", getmypid());
if (!socket_write($parent, $line, strlen($line))) {
socket_close($parent);
die(socket_strerror(socket_last_error()));
}
socket_close($parent);
exit(0);
}
}
示例4: createPair
/**
* Creates a pair of indistinguishable sockets and stores them in an array.
*
* <p>Creates two connected and indistinguishable sockets. This function is commonly used in IPC (InterProcess
* Communication).</p>
*
* @param int $domain <p>The domain parameter specifies the protocol family to be used by the socket. See
* <code>create()</code> for the full list.</p>
* @param int $type <p>The type parameter selects the type of communication to be used by the socket. See
* <code>create()</code> for the full list.</p>
* @param int $protocol <p>The protocol parameter sets the specific protocol within the specified domain to be used
* when communicating on the returned socket. The proper value can be retrieved by name by using
* <code>getprotobyname()</code>. If the desired protocol is TCP, or UDP the corresponding constants
* <code>SOL_TCP</code>, and <code>SOL_UDP</code> can also be used. See <code>create()</code> for the full list of
* supported protocols.
*
* @throws Exception\SocketException If the creation of the php sockets is not successful.
*
* @see Socket::create()
*
* @return Socket[] An array of Socket objects containing identical sockets.
*/
public static function createPair($domain, $type, $protocol)
{
$array = [];
$return = @socket_create_pair($domain, $type, $protocol, $array);
if ($return === false) {
throw new SocketException();
}
$sockets = self::constructFromResources($array);
foreach ($sockets as $socket) {
$socket->domain = $domain;
$socket->type = $type;
$socket->protocol = $protocol;
}
return $sockets;
}
示例5: __construct
/**
*
*/
public function __construct()
{
$this->tty_fd = fopen("/dev/tty", "r+b");
if (!$this->tty_fd) {
throw new InitalizationException("Cannot open /dev/tty");
}
$terminalDetector = new TerminalDetector();
$this->terminal = $terminalDetector->detect();
socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $this->winch_sockets);
$this->old_tty_settings = $this->getTtySettings();
$this->setTTYSettings(array('-ignbrk', '-brkint', '-ignpar', '-parmrk', '-inpck', '-istrip', '-inlcr', '-igncr', '-icrnl', '-ixon', '-ixoff', '-iuclc', '-ixany', '-imaxbel', '-opost', '-isig', '-icanon', '-iexten', '-parenb', 'cs8', 'time', '0', 'min', '0'));
$this->input_buffer = new ByteBuffer(128, $this->terminal);
$this->output_buffer = new ByteBuffer(32 * 1024, $this->terminal);
$this->output_buffer->putsFunc(TerminalFunc::T_ENTER_CA);
$this->output_buffer->putsFunc(TerminalFunc::T_ENTER_KEYPAD);
$this->output_buffer->putsFunc(TerminalFunc::T_HIDE_CURSOR);
$this->sendClear();
$this->updateTerminalSize();
pcntl_signal(SIGWINCH, array($this, 'sigwinchhandler'));
$this->back_buffer = new CellBuffer($this->term_width, $this->term_height, $this->foreground, $this->background);
$this->front_buffer = new CellBuffer($this->term_width, $this->term_height, $this->foreground, $this->background);
}
示例6: work
/**
* Execute a Closure as another process in the background while showing a
* status update. The status update can be an indefinite spinner or a string
* periodically sent from the background process, depending on whether the
* provided Closure object has a $socket parameter or not. Messaging to the
* main process is done by socket_* functions. The return value is either
* the return value of the background process, or false if the process fork
* failed.
*
* @param callable $callable Closure object
* @return bool|int
* @throws \Exception
*/
public static function work(\Closure $callable)
{
if (!extension_loaded('pcntl')) {
throw new \Exception('pcntl extension required');
}
if (!extension_loaded('sockets')) {
throw new \Exception('sockets extension required');
}
$spinner = array('|', '/', '-', '\\');
$i = 0;
$l = count($spinner);
$delay = 100000;
$func = new \ReflectionFunction($callable);
$socket = (bool) $func->getNumberOfParameters();
if ($socket) {
$sockets = array();
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
return false;
}
}
$pid = pcntl_fork();
if ($pid > 0) {
$done = false;
$retval = 0;
pcntl_signal(SIGCHLD, function () use($pid, &$done, &$retval) {
$child_pid = pcntl_waitpid($pid, $status);
if (pcntl_wifexited($status)) {
$retval = pcntl_wexitstatus($status);
}
$done = true;
});
if ($socket) {
$text = '';
while (!$done) {
$r = array($sockets[1]);
$w = null;
$e = null;
if ($status = socket_select($r, $w, $e, 0)) {
$data = socket_read($sockets[1], 4096, PHP_NORMAL_READ);
if ($data === false) {
throw new \Exception(sprintf('socket write error %s', socket_strerror(socket_last_error($sockets[1]))));
}
echo str_repeat(chr(8), strlen($text));
$text = rtrim($data, "\n");
Console::stdout($text);
} else {
pcntl_signal_dispatch();
}
usleep($delay);
}
echo str_repeat(chr(8), strlen($text));
socket_close($sockets[0]);
socket_close($sockets[1]);
} else {
while (!$done) {
pcntl_signal_dispatch();
echo $spinner[$i];
usleep($delay);
echo chr(8);
$i = $i === $l - 1 ? 0 : $i + 1;
}
}
return $retval;
} elseif ($pid === 0) {
if ($socket) {
call_user_func($callable, $sockets[0]);
} else {
call_user_func($callable);
}
exit;
} else {
// Unable to fork process.
return false;
}
}
示例7: create
/**
* Creates the worker pool (forks the children)
*
* Please close all open resources before running this function.
* Child processes are going to close all open resources uppon exit,
* leaving the parent process behind with invalid resource handles.
* @param \QXS\WorkerPool\WorkerInterface $worker the worker, that runs future tasks
* @throws \RuntimeException
* @throws WorkerPoolException
* @return WorkerPool
*/
public function create(WorkerInterface $worker)
{
if ($this->workerPoolSize <= 1) {
$this->workerPoolSize = 2;
}
$this->parentPid = getmypid();
$this->worker = $worker;
if ($this->created) {
throw new WorkerPoolException('The pool has already been created.');
}
$this->created = TRUE;
// when adding signals use pcntl_signal_dispatch(); or declare ticks
foreach ($this->signals as $signo) {
pcntl_signal($signo, array($this, 'signalHandler'));
}
// no Semaphore attached? -> create one
if (!$this->semaphore instanceof Semaphore) {
$this->semaphore = new Semaphore();
$this->semaphore->create(Semaphore::SEM_RAND_KEY);
} elseif (!$this->semaphore->isCreated()) {
$this->semaphore->create(Semaphore::SEM_RAND_KEY);
}
ProcessDetails::setProcessTitle($this->parentProcessTitleFormat, array('basename' => basename($_SERVER['PHP_SELF']), 'fullname' => $_SERVER['PHP_SELF'], 'class' => get_class($this)));
for ($i = 1; $i <= $this->workerPoolSize; $i++) {
$sockets = array();
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === FALSE) {
// clean_up using posix_kill & pcntl_wait
throw new \RuntimeException('socket_create_pair failed.');
break;
}
$processId = pcntl_fork();
if ($processId < 0) {
// cleanup using posix_kill & pcntl_wait
throw new \RuntimeException('pcntl_fork failed.');
break;
} elseif ($processId === 0) {
// WE ARE IN THE CHILD
$this->workerProcesses = new ProcessDetailsCollection();
// we do not have any children
$this->workerPoolSize = 0;
// we do not have any children
socket_close($sockets[1]);
// close the parent socket
$this->runWorkerProcess($worker, new SimpleSocket($sockets[0]), $i);
} else {
// WE ARE IN THE PARENT
socket_close($sockets[0]);
// close child socket
// create the child
$this->workerProcesses->addFree(new ProcessDetails($processId, new SimpleSocket($sockets[1])));
}
}
return $this;
}
示例8: create_pair
/**
* Creates a pair of sockets
*
*/
public static function create_pair($domain, $type, $protocol)
{
$created = @socket_create_pair($domain, $type, $protocol, $fd);
if ($created === false) {
throw new Socket_Exception("Failed to create socket pair", socket_last_error());
}
$ret = array(new self($fd[0]), new self($fd[1]));
return $ret;
}
示例9: index
function index($aResult, $sDatabaseDSN)
{
$oDB =& DB::connect($sDatabaseDSN . '?new_link=true', array('persistent' => false));
if (PEAR::IsError($oDB)) {
echo $oDB->getMessage() . "\n";
exit;
}
$oDB->setFetchMode(DB_FETCHMODE_ASSOC);
$oDB->query("SET DateStyle TO 'sql,european'");
$oDB->query("SET client_encoding TO 'utf-8'");
if (!isset($aResult['index-estrate']) || $aResult['index-estrate'] < 1) {
$aResult['index-estrate'] = 30;
}
if (getBlockingProcesses() > $aResult['max-blocking']) {
echo "Too many blocking processes for index\n";
exit;
}
if ($aResult['index-instances'] > 1) {
$aInstances = array();
for ($iInstance = 0; $iInstance < $aResult['index-instances']; $iInstance++) {
$aInstances[$iInstance] = array('iPID' => null, 'hSocket' => null, 'bBusy' => false);
socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $aSockets);
$iPID = pcntl_fork();
if ($iPID == -1) {
die('Could not fork Process');
}
if (!$iPID) {
// THIS IS THE CHILD PROCESS
// Reconnect to database - reusing the same connection is not a good idea!
$oDBChild =& DB::connect($sDatabaseDSN . '?new_link=true', array('persistent' => false));
if (PEAR::IsError($oDBChild)) {
echo $oDBChild->getMessage() . "\n";
exit;
}
$oDBChild->setFetchMode(DB_FETCHMODE_ASSOC);
$oDBChild->query("SET DateStyle TO 'sql,european'");
$oDBChild->query("SET client_encoding TO 'utf-8'");
socket_close($aSockets[1]);
$hSocket = $aSockets[0];
while ($sRead = socket_read($hSocket, 1000, PHP_BINARY_READ)) {
if ($sRead == 'EXIT') {
break;
}
$aSector = unserialize($sRead);
echo " - {$iInstance} processing " . $aSector['geometry_index'] . "\n";
indexSector($oDBChild, $aSector, $aResult['max-blocking'], $aResult['max-load']);
socket_write($hSocket, 'DONE');
echo " - {$iInstance} finished " . $aSector['geometry_index'] . "\n";
}
socket_close($hSocket);
exit;
// THIS IS THE END OF THE CHILD PROCESS
}
$aInstances[$iInstance]['iPID'] = $iPID;
socket_close($aSockets[0]);
socket_set_nonblock($aSockets[1]);
$aInstances[$iInstance]['hSocket'] = $aSockets[1];
}
}
// Re-index the new items
if (!isset($aResult['index-rank']) || !$aResult['index-rank']) {
$aResult['index-rank'] = 0;
}
for ($i = $aResult['index-rank']; $i <= 30; $i++) {
echo "Rank: {$i}";
$iStartTime = date('U');
flush();
$sSQL = 'select geometry_index(geometry,indexed,name),count(*) from placex where rank_search = ' . $i . ' and indexed = false and name is not null group by geometry_index(geometry,indexed,name)';
$sSQL .= ' order by count desc';
$aAllSectors = $oDB->getAll($sSQL);
if (PEAR::isError($aAllSectors)) {
var_dump($aAllSectors);
exit;
}
$iTotalNum = 0;
foreach ($aAllSectors as $aSector) {
$iTotalNum += $aSector['count'];
}
$iTotalLeft = $iTotalNum;
echo ", total to do: {$iTotalNum} \n";
flush();
$fRankStartTime = time();
$iTotalDone = 0;
$fRate = $aResult['index-estrate'];
foreach ($aAllSectors as $aSector) {
$aSector['rank'] = $i;
if ($aSector['rank'] == 21 && $aSector['geometry_index'] == 617467) {
echo "Skipping sector 617467 @ 21 due to issue\n";
continue;
}
while (getBlockingProcesses() > $aResult['max-blocking'] || getLoadAverage() > $aResult['max-load']) {
echo "System busy, pausing indexing...\n";
sleep(60);
}
$iEstSeconds = (int) ($iTotalLeft / $fRate);
$iEstDays = floor($iEstSeconds / (60 * 60 * 24));
$iEstSeconds -= $iEstDays * (60 * 60 * 24);
$iEstHours = floor($iEstSeconds / (60 * 60));
$iEstSeconds -= $iEstHours * (60 * 60);
$iEstMinutes = floor($iEstSeconds / 60);
//.........这里部分代码省略.........
示例10: socketCreatePair
/**
* Creates a pair of indistinguishable sockets and stores them in an array
*
* @param int $domain The protocol family to be used by the socket
* @param int $type The type of communication to be used by the socket
* @param int $protocol The specific protocol within the specified domain
* @param array $fd Reference to an array in which the two socket resources will be inserted
*/
public final function socketCreatePair($domain, $type, $protocol, array &$fd)
{
return socket_create_pair($domain, $type, $protocol, $fd);
}
示例11: executeFork
function executeFork()
{
$this->output("Spawning {$this->procCount} child processes.\n");
$this->children = array();
for ($fork = 0; $fork < $this->procCount; $fork++) {
$ok = socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $fd);
if (!$ok) {
throw new Exception("Could not create UNIX socket");
}
$pid = pcntl_fork();
if ($pid == 0) {
$this->isChild = true;
foreach ($this->sockets as $old) {
socket_close($old);
}
socket_close($fd[0]);
break;
} else {
if ($pid == -1) {
throw new Exception("Could not fork");
}
socket_close($fd[1]);
$this->children[] = $pid;
$this->sockets[] = $fd[0];
}
}
if ($this->isChild) {
$this->childNumber = $fork;
$this->channel = $fd[1];
$this->executeWorker();
socket_close($this->channel);
} else {
$this->executeParent();
}
}
示例12: createParentChildComm
/**
* Parent child communcation sockets creation
*/
private function createParentChildComm()
{
$this->log(self::LOG_LEVEL_NORMAL, 'Preparing inter-process communication sockets...');
$sockets = array();
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) {
throw new Exception(socket_strerror(socket_last_error()));
}
list($this->readerSocket, $this->writerSocket) = $sockets;
socket_set_nonblock($this->readerSocket);
socket_set_nonblock($this->writerSocket);
}
示例13: fork
/**
* Forks and creates a socket pair for communication between parent and child process
*
* @param resource $socket
*
* @return int PID if master or 0 if child
*/
private function fork(&$socket)
{
$pair = [];
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $pair) === false) {
$this->logger->error('{type}: Unable to create socket pair; ' . socket_strerror(socket_last_error($pair[0])), $this->logContext);
exit(0);
}
$PID = Qless::fork();
if ($PID !== 0) {
// MASTER
$this->childProcesses++;
$socket = $pair[0];
socket_close($pair[1]);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 0, 'usec' => 10000]);
// wait up to 10ms to receive data
return $PID;
}
$socket = $pair[1];
socket_close($pair[0]);
$reserved = str_repeat('x', 20240);
register_shutdown_function(function () use(&$reserved, $socket) {
// shutting down
if (null === ($error = error_get_last())) {
return;
}
unset($reserved);
$type = $error['type'];
if (!isset(self::$ERROR_CODES[$type])) {
return;
}
$this->logger->debug('Sending error to master', $this->logContext);
$data = serialize($error);
while (($len = socket_write($socket, $data)) > 0) {
$data = substr($data, $len);
}
});
return $PID;
}
示例14: array
<?php
$sockets = array();
socket_create_pair(strtoupper(substr(PHP_OS, 0, 3)) == "WIN" ? AF_INET : AF_UNIX, SOCK_STREAM, 0, $sockets);
$parent_sock = $sockets[0];
$child_sock = $sockets[1];
unset($sockets);
$pid = pcntl_fork();
if ($pid == -1) {
console("[-] Failed to fork");
define("THREADED", false);
} elseif ($pid) {
//Parent
socket_close($child_sock);
define("THREADED", true);
define("CHILD", false);
} else {
//Child
define("CHILD", true);
socket_close($parent_sock);
forking_runtime($child_sock);
posix_kill(getmypid(), 9);
}
function forking_runtime($IOsock)
{
global $sock, $buffer, $chunks;
socket_set_nonblock($IOsock);
$last = time();
while ($sock) {
buffer();
if ($last + 10 < time()) {
示例15: socket_shutdown
$this->bClosed = true;
socket_shutdown($this->sckSocket);
socket_close($this->sckSocket);
}
}
/*********************************************************************************
Main program start here
*********************************************************************************/
/* Loading modules */
include _MODULES_PATH_ . "plugwise_usb.php";
writelog("Starting Main Program...");
foreach ($process as $processname => $module) {
writelog("Creating IPC Socket for module {$processname} ...");
/* Trying to create socket pair */
/* Unable to create socket pair */
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $process[$processname]["socket"]) === false) {
writelog("socket_create_pair() a échoué. Raison : " . socket_strerror(socket_last_error()));
} else {
writelog("opening socket pair for {$processname} : OK");
/* Forking module*/
$pid = pcntl_fork();
/***********************************
/* Starting modules (child)
***********************************/
if (!$pid) {
switch ($module["bootstrap"]) {
case $process[$processname]["bootstrap"]:
writelog("Starting module {$processname} ...");
include _MODULES_PATH_ . $process[$processname]["driver"];
writelog($process[$processname]["bootstrap"] . ": finished");
exit(0);