/** * Init Tunnel. */ public function __construct() { $this->parentPID = getmypid(); $this->bridge = $this->createBridge(); $this->queue = msg_get_queue(ftok(__FILE__, 'k')); pcntl_signal(POLL_MSG, [$this, 'read']); }
/** * Memory alloc */ protected function alloc() { if (null !== $this->memory) { return; } $this->memory = shm_attach(ftok(__FILE__, $this->identifier), $this->segmentSize, 0644); }
function Server($address = '0', $port = 8001, $verboseMode = false) { $this->console("Server starting..."); $this->address = $address; $this->port = $port; $this->verboseMode = $verboseMode; // socket creation $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); if (!is_resource($socket)) { $this->console("socket_create() failed: " . socket_strerror(socket_last_error()), true); } if (!socket_bind($socket, $this->address, $this->port)) { $this->console("socket_bind() failed: " . socket_strerror(socket_last_error()), true); } if (!socket_listen($socket, 20)) { $this->console("socket_listen() failed: " . socket_strerror(socket_last_error()), true); } $this->master = $socket; $this->sockets = array($socket); $this->console("Server started on {$this->address}:{$this->port}"); // Creating a Shared Memory Zone in RAM $this->console("Trying to allocate memory"); $shm_key = ftok(__FILE__, 't'); $shm_size = 1024 * 1024; // 1MB $this->shm = shm_attach($shm_key, $shm_size); // Launching... $this->run(); }
public function shutdown() { $this->queue = msg_get_queue(ftok($this->file, 'R'), 0777); for ($i = 0; $i < $this->numThreads * 2; $i++) { msg_send($this->queue, 100 + $i, 'shutdown'); } }
protected function settingCheck(&$setting) { //有一些配置是DIServer运行必须控制的。 if ($setting['task_worker_num'] <= 0) { throw new BootException("Error: 配置swoole.task_worker_num被设置为0。"); } if ($setting['task_ipc_mode'] != 2) { throw new BootException("Error: 配置swoole.task_ipc_mode设置不是2。"); } if ($setting['dispatch_mode'] == 1 || $setting['dispatch_mode'] == 3) { throw new BootException("Error: 配置swoole.dispatch_mode=1/3时,底层会屏蔽onConnect/onClose事件,原因是这2种模式下无法保证onConnect/onClose/onReceive的顺序。"); } if (isset($setting['chroot'])) { throw new BootException("Error: 配置swoole.chroot会导致autoloader无法在工作\\任务进程正常使用,请确定你能处理(如修改autoloader的路径)然后过来注释这个异常。"); } if (!isset($setting['package_eof'])) { $setting['package_eof'] = ''; //疑似swoole bug,如果不显式指定package_eof则无法正常收包。 } if (!isset($setting['task_tmpdir'])) { $setting['task_tmpdir'] = Application::GetServerPath('/Runtimes/TaskTemp'); } if (!isset($setting['log_file'])) { $setting['log_file'] = Application::GetServerPath('/Runtimes/Log/' . Application::GetServerName() . '.log'); } if (!isset($setting['message_queue_key'])) { $setting['message_queue_key'] = ftok(Application::GetServerPath(), 0); } $setting['daemonize'] = DI_DAEMONIZE; }
/** * Return a number representing the current queue. * @return integer */ private function getKey() { if ($this->_key === null) { $this->_key = ftok(__FILE__, $this->id); } return $this->_key; }
function Map2GE($x, $y) { if (0) { $SHM_KEY = ftok(__FILE__, chr(4)); $data = shm_attach($SHM_KEY, 102400, 0666); $result = shm_get_var($data, 1); $r = $result[$x][$y]; if (isset($r)) { shm_detach($data); return $r; } } // ×¥¿ $r = t67to97($x, $y); $x = $r[0]; $y = $r[1]; $proj = "proj -I +proj=tmerc +ellps=aust_SA +lon_0=121 +x_0=250000 +k=0.9999"; $ret = shell_exec("echo {$x} {$y} | {$proj}"); if (preg_match("/(\\d+)d(\\d+)'([\\d.]+)\"E\\s+(\\d+)d(\\d+)'([\\d.]+)\"N/", $ret, $matches)) { list($junk, $ed, $em, $es, $nd, $nm, $ns) = $matches; $r[0] = $ed + $em / 60 + $es / 3600; $r[1] = $nd + $nm / 60 + $ns / 3600; if (0) { $result[$x][$y] = $r; shm_put_var($data, 1, $result); shm_detach($data); } return $r; } return FALSE; // exit; }
/** * Memory alloc */ protected function alloc() { if (null !== $this->memory) { return; } $this->memory = shmop_open(ftok(__FILE__, $this->identifier), "c", 0644, $this->segmentSize); }
public function __construct($queue_file) { if (!file_exists($queue_file)) { throw new Exception("Could not find mailbox: {$queue_file}"); } $this->queue_id = msg_get_queue(ftok($queue_file, 'r'), 0666); }
/** * generate IPC key * * @return int */ public function generate() { if (!file_exists($this->pathname)) { touch($this->pathname); } return ftok($this->pathname, 'S'); }
public function init() { $project = chr(getmypid() % 26 + 65); $dir = Yii::getPathOfAlias('application.runtime.cache'); if (!is_dir($dir)) { mkdir($dir); } $this->fileName = $dir . DIRECTORY_SEPARATOR . 'cache_' . $project . ".dump"; try { $shmKey = ftok(__FILE__, $project); if ($shmKey < 0) { throw new CException('Bad ftok'); } $this->shmId = @shmop_open($shmKey, "c", 0644, $this->maxSize); if ($this->shmId == 0) { throw new CException('Bad shmop'); } $try = @unserialize(shmop_read($this->shmId, 0, 0)); $this->offsetWrite = (int) $try; if ($this->offsetWrite == 0) { $this->saveOffsetWrite(true); } else { $this->detectStart(); } } catch (Exception $e) { Yii::log('Unable to init shared memory', CLogger::LEVEL_ERROR, 'sharedMemory'); } }
public function initialize() { if ($this->queuePath) { return; } $this->queuePath = KATATMP . 'queue' . DS; if (defined('QUEUE_IDENTIFIER')) { $this->queueId = QUEUE_IDENTIFIER; } else { if (defined('CACHE_IDENTIFIER')) { $this->queueId = (int) hexdec(md5(CACHE_IDENTIFIER)); } else { $this->queueId = ftok(__FILE__); } } switch ($this->method) { case null: throw new Exception('You have to setMethod() first'); break; case self::QM_MSGQUEUE: $this->queueRes = msg_get_queue($this->queueId, 0666); break; case self::QM_ZEROMQ: break; case self::QM_LIBEVENT: break; case self::QM_FILESOCKET: break; case self::QM_FILESYS: break; } //switch }
private function __construct() { /* if wndows */ /* function ftok($pathname, $proj_id) { $st = @stat($pathname); if (!$st) { return -1; } $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24))); return $key; */ $shm_key = ftok(__FILE__, 't'); $this->mShmId = shmop_open($shm_key, 'ac', 0, 0); if ($this->mShmId) { #it is already created //echo '#it is already created'; } else { #you need to create it with shmop_open using "c" only //echo '#you need to create it with shmop_open using "c" only'; $this->mShmId = shmop_open($shm_key, 'c', $this->_SHM_AC_, $this->_SHM_SIZE_); } $this->mShmId = shmop_open($shm_key, 'w', 0, 0); //echo 'ShmId:'.$this->mShmId; $this->ShmIsClean = false; }
/** * Provides Mutex factories. * * @return callable[][] The mutex factories. */ public function provideMutexFactories() { $cases = ["NoMutex" => [function () { return new NoMutex(); }], "TransactionalMutex" => [function () { $pdo = new \PDO("sqlite::memory:"); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return new TransactionalMutex($pdo); }], "FlockMutex" => [function () { vfsStream::setup("test"); return new FlockMutex(fopen(vfsStream::url("test/lock"), "w")); }], "SemaphoreMutex" => [function () { return new SemaphoreMutex(sem_get(ftok(__FILE__, "a"))); }], "SpinlockMutex" => [function () { $mock = $this->getMockForAbstractClass(SpinlockMutex::class, ["test"]); $mock->expects($this->any())->method("acquire")->willReturn(true); $mock->expects($this->any())->method("release")->willReturn(true); return $mock; }], "LockMutex" => [function () { $mock = $this->getMockForAbstractClass(LockMutex::class); $mock->expects($this->any())->method("lock")->willReturn(true); $mock->expects($this->any())->method("unlock")->willReturn(true); return $mock; }]]; if (getenv("MEMCACHE_HOST")) { $cases["MemcacheMutex"] = [function () { $memcache = new Memcache(); $memcache->connect(getenv("MEMCACHE_HOST")); return new MemcacheMutex("test", $memcache); }]; $cases["MemcachedMutex"] = [function () { $memcache = new Memcached(); $memcache->addServer(getenv("MEMCACHE_HOST"), 11211); return new MemcachedMutex("test", $memcache); }]; } if (getenv("REDIS_URIS")) { $uris = explode(",", getenv("REDIS_URIS")); $cases["PredisMutex"] = [function () use($uris) { $clients = array_map(function ($uri) { return new Client($uri); }, $uris); return new PredisMutex($clients, "test"); }]; $cases["PHPRedisMutex"] = [function () use($uris) { $apis = array_map(function ($uri) { $redis = new Redis(); $uri = parse_url($uri); if (!empty($uri["port"])) { $redis->connect($uri["host"], $uri["port"]); } else { $redis->connect($uri["host"]); } return $redis; }, $uris); return new PHPRedisMutex($apis, "test"); }]; } return $cases; }
function rm($key) { $this->shmop_key = ftok($this->pre . $key); $this->shmop_id = shmop_open($this->shmop_key, 'c', 0644, 0); $result = shmop_delete($this->shmop_id); shmop_close($this->shmop_id); return $result; }
/** * @param EventDispatcherInterface $dispatcher * @param array $customEvents Custom events to proxy to parent process. */ public function __construct(EventDispatcherInterface $dispatcher, array $customEvents = []) { $this->dispatcher = $dispatcher; $class = new \ReflectionClass('\\Unteist\\Event\\EventStorage'); $this->events = array_unique(array_values($class->getConstants() + $customEvents)); $this->parentPID = getmypid(); $this->queue = msg_get_queue(ftok(__FILE__, 'U')); }
/** * @param $ipc_filename * @param $msg_type * @return int * @throws Exception */ public function get_ipc_key($ipc_filename, $msg_type) { $key_t = \ftok($ipc_filename, $msg_type); if ($key_t == 0) { throw new \Exception('ftok error'); } return $key_t; }
/** * generate IPC key * * @return int */ private function genId() { $pathname = '/tmp/' . sha1($this->getKey()); if (!file_exists($pathname)) { touch($pathname); } return ftok($pathname, 'S'); }
/** * generates a key for memory access baesd on the file path * @return int */ private function getBlockKey() { if (function_exists("ftok")) { return ftok(__FILE__, 't'); } else { return 1946559754; } }
public function open() { $perms = $this->config['shared_memory.permissions']; $size = $this->config['rabbitmq.max_workers'] * 44; $file = $this->tmp_file; $this->shm_res = shm_attach(ftok($file, 'L'), $size, $perms); $this->logger->debug('Opening shared memory resource with id: [' . intval($this->shm_res) . '] on file [' . $this->tmp_file . ']'); }
public function __construct($file) { // set shmop keys $this->_dataLengthShmKey = ftok($file, 'a'); $this->_dataShmKey = ftok($file, 'b'); // set shmop for data length $this->_dataLengthShm = shmop_open($this->_dataLengthShmKey, 'c', 0644, self::DATALENGTH_LENGTH); }
protected function getKeyId($key) { $file = $this->getFTok($key); if (!file_exists($file)) { touch($file); } return ftok($file, 'j'); }
protected function getKey($id) { $keyfile = $this->getKeyFile($id); if (!file_exists($keyfile)) { touch($keyfile); } return ftok($keyfile, 'R'); }
/** * Create shared memory block */ private function attach() { $this->__key = ftok($this->__path, $this->__proj_id); $this->__shm = shm_attach($this->__key, $this->__size); //allocate shared memory $this->__mutex = sem_get($this->__key, 1); //create mutex with same key }
/** * Provides shared Storage implementations. * * @return callable[][] Storage factories. */ public function provideStorageFactories() { $cases = [[function ($name) { return new SessionStorage($name); }], [function ($name) { vfsStream::setup('fileStorage'); return new FileStorage(vfsStream::url("fileStorage/{$name}")); }], [function ($name) { $key = ftok(__FILE__, $name); return new IPCStorage($key); }], [function ($name) { $pdo = new \PDO("sqlite::memory:"); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return new PDOStorage($name, $pdo); }]]; if (getenv("MYSQL_DSN")) { $cases[] = [function ($name) { $pdo = new \PDO(getenv("MYSQL_DSN"), getenv("MYSQL_USER")); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT, false); $storage = new PDOStorage($name, $pdo); $pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT, true); return $storage; }]; } if (getenv("PGSQL_DSN")) { $cases[] = [function ($name) { $pdo = new \PDO(getenv("PGSQL_DSN"), getenv("PGSQL_USER")); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return new PDOStorage($name, $pdo); }]; } if (getenv("MEMCACHE_HOST")) { $cases[] = [function ($name) { $memcache = new \Memcache(); $memcache->connect(getenv("MEMCACHE_HOST")); return new MemcacheStorage($name, $memcache); }]; $cases[] = [function ($name) { $memcached = new \Memcached(); $memcached->addServer(getenv("MEMCACHE_HOST"), 11211); return new MemcachedStorage($name, $memcached); }]; } if (getenv("REDIS_URI")) { $cases["PHPRedisStorage"] = [function ($name) { $uri = parse_url(getenv("REDIS_URI")); $redis = new Redis(); $redis->connect($uri["host"]); return new PHPRedisStorage($name, $redis); }]; $cases["PredisStorage"] = [function ($name) { $redis = new Client(getenv("REDIS_URI")); return new PredisStorage($name, $redis); }]; } return $cases; }
function pleac_Sharing_Variables_in_Different_Processes() { // sharetest - test shared variables across forks $SHM_KEY = ftok(__FILE__, chr(1)); $handle = sem_get($SHM_KEY); $buffer = shm_attach($handle, 1024); // The original recipe has an INT signal handler here. However, it // causes erratic behavior with PHP, and PHP seems to do the right // thing without it. for ($i = 0; $i < 10; $i++) { $child = pcntl_fork(); if ($child == -1) { die('cannot fork'); } elseif ($child) { $kids[] = $child; // in case we care about their pids } else { squabble(); exit; } } while (true) { print 'Buffer is ' . shm_get_var($buffer, 1) . "\n"; sleep(1); } die('Not reached'); function squabble() { global $handle; global $buffer; $i = 0; $pid = getmypid(); while (true) { if (preg_match("/^{$pid}\\b/", shm_get_var($buffer, 1))) { continue; } sem_acquire($handle); $i++; shm_put_var($buffer, 1, "{$pid} {$i}"); sem_release($handle); } } // Buffer is 14357 1 // Buffer is 14355 3 // Buffer is 14355 4 // Buffer is 14354 5 // Buffer is 14353 6 // Buffer is 14351 8 // Buffer is 14351 9 // Buffer is 14350 10 // Buffer is 14348 11 // Buffer is 14348 12 // Buffer is 14357 10 // Buffer is 14357 11 // Buffer is 14355 13 // ... }
/** * @throws \RuntimeException */ protected function init() { $file = sprintf("%s/%s", sys_get_temp_dir(), base64_encode($this->identifier)); @touch($file); $this->queue = msg_get_queue(ftok($file, 'm')); if (!$this->queue) { throw new \RuntimeException("Unable to get message queue"); } }
public function __construct($channel) { $this->ipcFile = sys_get_temp_dir() . "/{$channel}.ipc"; @touch($this->ipcFile); $this->ipc = ftok($this->ipcFile, 's'); // s for shm $this->ipc = shm_attach($this->ipc); // leave $memsize to php.ini }
/** * Constructor. * * @param string name File name to use to generate the semaphore key. */ public function __construct($name) { $this->count = 0; $this->semKey = ftok($name, 'R'); $this->semId = sem_get($this->semKey); if (!is_resource($this->semId)) { throw new \Exception('Unable to create semaphore'); } }
private function setupSegment() { $id = ftok($this->file, 't'); if ($id === -1) { throw new Exception('could not creating semaphore segment (ftok)'); } $this->id = $id; $this->sid = shmop_open($id, 'c', 0644, 100); }