1#!/bin/bash
2#
3# This is just an example of using poll(). Naturally you wouldn't use ctypes to
4# do something this simple, but managing lots of blocking file descriptors in
5# bash is much easier with native system features like poll.
6#
7
8source ctypes.sh
9
10declare -ri POLLIN=1
11declare -ri POLLPRI=2
12declare -ri POLLOUT=4
13declare -ri POLLERR=8
14
15struct pollfd fds
16
17# Allocate memory
18dlcall -r pointer -n fdsptr malloc $(sizeof pollfd)
19
20# Let's monitor stdin
21fds[fd]=$STDIN_FILENO
22fds[events]=short:$POLLIN
23
24# convert that bash struct to a native struct
25pack $fdsptr fds
26
27while true; do
28    echo waiting for file descriptor to be ready...
29    dlcall poll $fdsptr 1 -1
30
31    # convert native struct back to bash struct so we can read revents
32    unpack $fdsptr fds
33
34    # was the POLLIN (read ready) bit set?
35    if ((${fds[revents]##*:} & POLLIN)); then
36        echo read will not block...
37        read
38        echo you will see me immediately!
39    fi
40done
41