First, non-blocking I/O works on sockets and pipes, but not on regular files. That is not a limit of Perl but of the underlying system. What you instead want for regular files would not be non-blocking but asynchronous I/O:
- non-blocking I/O: operation will not block when it can not be finished immediately but it will do as much as it can and then return.
- asynchronous I/O: the operation will be done in the background and the application will be notified once it is done.
Unfortunately support for real asynchronous I/O is system specific and often not well supported so you would need to use threads here (again, that's not a problem of Perl but of the underlying system). You might want to take a look at IO::AIO which tries to give you the feeling of asynchronous I/O by using whatever the system supports. But note also that it is not very efficient and if you could use non-blocking sockets directly (i.e. with sockets but not with regular files) you should do it.
To use non-blocking you have to mark the file descriptor as non-blocking and then you read, write, connect, accept etc on it like you do normally, except that it will never block but return EAGAIN
/EWOULDBLOCK
if the operation can not be executed immediately. To wait until a file descriptor becomes readable/writable again you can use select
, poll
, kqueue
or similar mechanisms.
That's for a short introduction. Some things you have to watch out for:
- Setting a file descriptor to non-blocking is different on UNIX and Windows.
IO::Socket->blocking
handles the major differences for you.
- On todays UNIX
EAGAIN
is the same as EWOULDBLOCK
but on Windows this is different and you have usually to use EWOULDBLOCK
.
- Again, non-blocking does not work on regular files. It might not throw an error but will simply block.
- You have to watch out if you want to use non-blocking with file descriptors which do not reside entirely in the kernel (like with SSL sockets). Look at the documentation of IO::Socket::SSL for more information.