2018-04-15 14:41:46 +00:00
|
|
|
noccylabs/ipc
|
|
|
|
=============
|
|
|
|
|
|
|
|
This is a one-size-fits-all IPC library to facilitate communication between
|
2018-04-15 16:27:51 +00:00
|
|
|
threads and processes.
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
For complete examples, see the `examples` directory in the source tree.
|
|
|
|
## Signals
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
Asynchronous signals are automatically enabled if supported. Otherwise, the
|
|
|
|
`pcntl_signal_dispatch()` method must be frequently called from your main loop.
|
|
|
|
You can test for this using the `ASYNC_SIGNALS` constant:
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
if (!ASYNC_SIGNALS) {
|
|
|
|
pcntl_signal_dispatch();
|
|
|
|
}
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
### Signal handlers
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
Signal handlers allow for multiple listeners, with any one of them being able to
|
|
|
|
prevent the signal from bubbling up.
|
2018-04-15 14:41:46 +00:00
|
|
|
|
2018-04-15 16:27:51 +00:00
|
|
|
$handler = new SignalHandler(SIGUSR1);
|
|
|
|
|
|
|
|
$handler->addHandler(function () {
|
|
|
|
// Handle SIGUSR1, return true to stop bubbling
|
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
|
|
|
You can also handle as well as fire signals using the `Signal` class:
|
|
|
|
|
|
|
|
$signal = new Signal(SIGUSR1);
|
|
|
|
$signal->setHandler(function () {
|
|
|
|
// Handle SIGUSR1
|
|
|
|
});
|
|
|
|
|
|
|
|
// Dispatch the signal to ourselves
|
|
|
|
(new Signal(SIGUSR1))->dispatch($pid);
|
|
|
|
|
|
|
|
|
|
|
|
### Signal traps
|
|
|
|
|
|
|
|
Traps are used in the main loop to break on signals
|
|
|
|
|
|
|
|
$trap = new SignalTrap(SIGINT);
|
|
|
|
|
|
|
|
while (!$trap->isTrapped()) {
|
|
|
|
// ...
|
|
|
|
}
|
|
|
|
|
|
|
|
## Timers
|
|
|
|
|
|
|
|
Timers fire asynchronously at fixed 1 second intervals. It requires signals to be
|
|
|
|
processed; see above.
|
|
|
|
|
|
|
|
$timer = new Timer(function () {
|
|
|
|
echo ".";
|
|
|
|
});
|
|
|
|
|
|
|
|
## File locks
|
|
|
|
|
|
|
|
File locks uses a shared file as a resource for locking.
|
|
|
|
|
|
|
|
// Creating the lock will not acquire it
|
|
|
|
$lock = new FileLock(__FILE__);
|
|
|
|
|
|
|
|
if (!$lock->acquire()) {
|
|
|
|
echo "fail!\n";
|
|
|
|
} else {
|
|
|
|
$lock->release();
|
|
|
|
}
|
|
|
|
|
|
|
|
## SysV wrappers
|
|
|
|
|
|
|
|
### Semaphores
|
|
|
|
|
|
|
|
### Mutexes
|
|
|
|
|
|
|
|
### Messagae Queues
|
|
|
|
|
|
|
|
## Communication
|
|
|
|
|
|
|
|
### Channels
|
|
|
|
|
|
|
|
Channels are essentially connected pipes. A channel can be created with a stream resource,
|
|
|
|
or through the `createPair()` factory method.
|
|
|
|
|
|
|
|
[ $ch1, $ch2 ] = StreamChannel::createPair();
|
|
|
|
$ch1->send($data);
|
|
|
|
$rcvd = $ch2->receive();
|