Hi,
I'm an experienced programmer (mostly Python the last few years) but relatively new to nim. I like nim but sometimes find it difficult to locate examples of how to accomplish relatively simple things. For example, I decided to try to use the posix "poll" function to check whether a file descriptor has data to read. I've looked at the std/posix page, scanned various books and tutorials on nim, and searched the internet, but so far have been unable to find a single example of working nim code that calls poll. Can anyone provide an example or point me to one? If I see one I can probably figure out how to modify it for my use case.
I don't think there's any point in posting my failed attempts to get my poll call to compile, but I think my problem is in constructing and specifying the a1 argument to:
proc poll(a1: ptr TPollfd; a2: Tnfds; a3: cint): cint {.importc,
header: "<poll.h>", sideEffect, ....}
I haven't figured out how to translate from a sequence of TPollfd to the pointer required for a1.
Thanks for any help you can provide.
I'm an experienced programmer (mostly Python the last few years)
These are two mutually exclusive properties. Sorry, couldn't resist. ;-)
As for your question, I don't know, everybody uses the selectors.nim stdlib module.
BTW, asking Claude or GPT5 to give you examples of these parts of Nim can be really helpful. There's plenty of Nim code that uses poll and the like but it's just not documented. LLMs are pretty great at that now! I use them routinely to remind me of some syntax, or library api, etc.
Claude gave me this snippet: let result = poll(addr fds[0], 1, cint(timeoutMs)) # Call poll with timeout in milliseconds
As I understand it, std/posix is a thin wrapper, so you need to know how the C API works to use it.
If I were in your place, I would first check the system manual for poll (e.g., man poll on any POSIX system). Then I would look up online examples in C and translate them to Nim.
Also, github is a good tool for searching working Nim code. Here is a couple examples for TPollFD.
Thanks @janAkali for your comment. I've actually used lots of posix stuff in other languages, such as C, C++, etc. As a newcomer to nim, for me the tricky part was translating from C to nim. I have the following test code working in nim-2.2.4:
import posix, math
# Poll for input on a specified file (default stdin) with a specified timeout in seconds
# (default 0.0). Return 1 if a line ready to read, or 0 if timeout.
#
proc PollInputFile( file: File = stdin, timeoutsec: float64 = 0.0): bool =
var pollfds: seq[ TPollfd]
pollfds.add( TPollfd( fd: file.getFileHandle, events: POLLIN))
poll( addr pollfds[ 0], 1.Tnfds, (1000 * timeoutsec).round.cint).bool
echo "1st"
if PollInputFile( timeoutsec = 10.0): echo stdin.readLine
echo "2nd"
if PollInputFile( timeoutsec = 10.0): echo stdin.readLine
echo "done"