note 125458 added to function.pcntl-alarm

From: Date: Sat, 24 Oct 2020 20:25:54 +0000
Subject: note 125458 added to function.pcntl-alarm
Groups: php.notes 
Request: Send a blank email to php-notes+get-215636@lists.php.net to get a copy of this message
This is that universal timeout functionality you dreamed about and always wanted to have and guess what - it's as reliable as it gets, it's basically bulletproof. It can interrupt absolutely anything you throw at it and more, you name it - socket_connect(), socket_read(), fread(), infinite while() loops, sleep(), semaphores - seriously, any blocking operation. You can specify your own handler and just get over anything that normally would make your code unresponsive. <?php /** * Because we shouldn't handle asynchronous * events in synchronous manner. */ pcntl_async_signals(TRUE); /** * Some flag we can change to know for sure * that our operation timed out. */ $timed_out = FALSE; /** * Register SIGALRM signal handler to avoid * getting our process killed when signal arrives. */ pcntl_signal(SIGALRM, function($signal) use ($timed_out) { $timed_out = TRUE; }); /** * Now we set our timeout for 2 seconds, but it's not set in stone * we can call pcntl_alarm() anytime to extend or to turn if off. */ pcntl_alarm(2); /** * Here we do something with unpredictable outcome that could * possibly block our program for a very long time. * I like sockets as an example, but it can be anything. */ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $connection = socket_connect($socket, 'irc.ircnet.com', 6667); /** * If our blocking operation didn't timed out then * timer is still ticking, we should turn it off ASAP. */ $timed_out || pcntl_alarm(0); /** * And now we do whatever we want to do. */ $status = $connection ? 'Connected.' : ($timed_out ? 'Timed out.' : socket_strerror(socket_last_error($socket))); echo 'STATUS: '. $status . PHP_EOL; ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.174 (proxied: 188.121.2.70) ---- Manual Page -- http://php.net/manual/en/function.pcntl-alarm.php Edit -- https://master.php.net/note/edit/125458 Del: integrated -- https://master.php.net/note/delete/125458/integrated Del: useless -- https://master.php.net/note/delete/125458/useless Del: bad code -- https://master.php.net/note/delete/125458/bad+code Del: spam -- https://master.php.net/note/delete/125458/spam Del: non-english -- https://master.php.net/note/delete/125458/non-english Del: in docs -- https://master.php.net/note/delete/125458/in+docs Del: other reasons-- https://master.php.net/note/delete/125458 Reject -- https://master.php.net/note/reject/125458 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#215636) next »